# -*- coding: utf-8 -*-

# !usr/bin/env python

# 判斷s是否是迴文字符串

def isHuiwen(s):

# 法一(不建議用此方法,看似簡單,但效率低,而且還要申請空間)

# return s == s[::-1] and s!=''

# 法二

if '' == s:

return False

else:

for x in range(len(s)//2):

if s[x]!=s[-x-1]:

return False

return True

# 獲取字符串的所有子串

def getAllChildString(L):

result = [L[x:x+1+i] for i in range(len(L)) for x in range(len(L)-i)] # L='abc' result = ['a', 'b', 'c', 'ab', 'bc', 'abc']

# result = [ [L[x:x+1+i] for x in range(len(L)-i)] for i in range(len(L)) ] # L='abc' result = [['a', 'b', 'c'], ['ab', 'bc'], ['abc']]

return result

# 返回所有迴文串

def getAllHuiwen(L):

childString = getAllChildString(L)

return list(filter(isHuiwen, childString))

# 返回最長迴文串(法一):獲取所有字串,依次判斷是否是迴文字符串,效率不高

def getMaxHuiwen1(L):

childString = getAllChildString(L)

for x in range(len(childString)): # 從最長的字串開始找,節省時間

if isHuiwen(childString[-x-1]):

return childString[-x-1]

return ''

a = 'adaelele'

print(getAllHuiwen(a))

print(getMaxHuiwen1(a))

查看原文 >>
相關文章