回文,返回字符串中最长的回文串
程序员文章站
2024-02-25 09:40:58
...
# -*- 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))
上一篇: 解决MySQL忘记密码问题的方法
下一篇: Python学习之路(一)