编写一个程序,查找给定的最长回文子串 串。尽量提高效率! 我编写了程序,但需要改进
A=input("write?")
def longestPalindrome(A):
rev = A[::-1]
l = len(A)
while l > 0:
for i in range(0, len(A) - l + 1):
half = int(l / 2)
left = A[i : i + half]
right = rev[len(A) - (i + l) : len(A) - (i + l - half)]
if left == right:
return A[i:i+l]
l -= 1
return None
print (longestPalindrome(A))
答案 0 :(得分:0)
请检查以下代码。
from itertools import combinations
from collections import Counter
sam = 'abcbarascalacsarijkl'
palindrome = []
for i,j in filter(lambda x: x[1] >1,Counter(sam).items()):
indexes = [index for index in range(len(sam)) if sam[index] == i]
for cm in combinations(indexes,2):
substr = sam[cm[0]:cm[1]+1]
if substr==substr[::-1]:
print('palindrome')
palindrome.append((substr,len(substr)))
sorted(palindrome,key=lambda x: x[1], reverse=True)[0][0]