Write a function that finds the longest palindromic substring of a given string. Try to be as efficient as possible!
If you find more than one substring you should return the one which is closer to the beginning.
Input: A text as a string.
Output: The longest palindromic substring.
Precondition: 1 < |text| ≤ 20
The text contains only ASCII characters.
解法一:
# 判断是否回文 def isPalindrome(s, start, end): while start < end: if s[start] != s[end]: return False start += 1 end -= 1 return True def longest_palindromic(s): max, left, right = 0, 0, 0 for i in range(len(s)): j = i+1 while j < len(s): if isPalindrome(s, i, j): if (j-i+1) > max: left, right = i, j max = j - i + 1 j += 1 print (left, right, max) return s[left:right+1]
循环穷举,范围从小到大。
解法二:
# 0:9 0:8 1:9 .... def longest_palindromic(text): s = len(text) for size in range(s)[::-1]: for index in range(s - size): word = text[index:index + size + 1] if word == word[::-1]: return word同样穷举,范围从大到小。
解法三:
from itertools import combinations as C def longest_palindromic(text): subs = (text[start: end] for start, end in C(range(len(text) + 1), 2)) print(list(C(range(len(text) + 1), 2))) return max((s for s in subs if s == s[::-1]), key=len)其中的subs = (text[start: end] for start, end in C(range(len(text) + 1), 2))语句,直接穷举出text字符串所有的子串,此方法很python。