【发布时间】:2020-10-31 11:03:26
【问题描述】:
最近 Twitter 提出了这个问题:
回文是一个前后读相同的字符序列。给定一个字符串 s,找出 s 中最长的回文子串。
例子:
Input: "banana"
Output: "anana"
Input: "million"
Output: "illi"
class Solution:
def longestPalindrome(self, s):
# Fill this in.
# Test program
s = "tracecars"
print(str(Solution().longestPalindrome(s)))
# racecar
所以我就这样解决了
class Solution:
def longestPalindrome(self, s):
index = 0
longestPalindrome = ""
for x in s:
subStr = s[index + 1:]
nextIndex = subStr.find(x)
while nextIndex != -1:
txt = x + subStr
pland = txt[:nextIndex + 2]
if self.isPalindromicSubString(pland):
if len(pland) > len(longestPalindrome):
longestPalindrome = pland
nextIndex = subStr.find(x,nextIndex + 1)
index = index + 1
return longestPalindrome
def isPalindromicSubString(self,subStr):
index = 0
reverseIndex = -1
isItPalindromic = True
for y in subStr:
if y != subStr[reverseIndex]:
isItPalindromic = False
index = index + 1
reverseIndex = reverseIndex - 1
return isItPalindromic
# Test program
s = "abcdef aka"
print(str(Solution().longestPalindrome(s)))
# racecar
效果很好,时间复杂度为 O(N^2) 有什么方法可以做得更好,并给我关于时间和空间复杂度的cmets
【问题讨论】:
-
最后,似乎即使是众所周知的解决方案最终仍然是 O(N^2)
-
@h0r53 来自维基百科文章:>[Manacher 算法] 为最长回文子串问题提供了线性时间解
-
谢谢,我只知道这是一个众所周知的问题,我已经解决了,但我想知道它是否可以通过更好的解决方案来解决
-
@h0r53 实际上它在 for 循环中包含 while 循环,所以它可能是 o(n^2) alog
标签: python performance optimization