四种解法:
(1)Brute Force:
枚举全部子串(是一个排列问题,共种),判断子串是否回文。时间复杂度
,空间复杂度
。
(2)动态规划法,同我的心路。
Python源码:
我的心路:
到目前为止数组、字符串的题目已经做了大约十道,过程中发现使用效果上:嵌套遍历<字典<指针。因此,设置了左指针和右指针,分别指向以迭代符i为(概念)中心的两侧,对比以当前i为中心的最长回文和目前为止最长的回文子串长度,对后者进行更新。之所以称迭代符i为“概念”中心,是因为字符串中会出现相邻字符相同的情况,遇到该种情况时,我将右指针向右,直到右指针指向的字符和i处字符不同,或右指针来到字符串结尾,与此同时将i与右指针同步后移,以避免重复计算相同一组回文序列。
实现花了一段时间。对比五个月前,自己的代码在速度上还是有所提高。很自然地想到了动态规划解法,我真是太棒啦(>^ω^<)。
Runtime: 84 ms, faster than 93.36% of Python online submissions for Longest Palindromic Substring.
Memory Usage: 11.7 MB, less than 82.19% of Python online submissions for Longest Palindromic Substring.
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
max_len = 0
max_sub = ''
i = 0
while i <= len(s) - 1:
l = i - 1
r = i
while(r <= len(s) - 1 and s[l + 1] == s[r]):
r += 1
i += 1
while(l >= 0 and r <= len(s) - 1 and s[l] == s[r]):
l -= 1
r += 1
if max_len < r - l - 1:
max_len = r - l - 1
max_sub = s[l+1:r]
return max_sub
Runtime: 1952 ms, faster than 41.26% of Python online submissions for Longest Palindromic Substring.
Memory Usage: 11.8 MB, less than 61.64% of Python online submissions for Longest Palindromic Substring.
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if(len(s) < 2):
return s
max_len = 0
result = ''
# for odd substring
for i in range(len(s)):
cnt = 0
result_tmp = ''
for j in range(i + 2):
if j <= i and i + j < len(s) and s[i + j] == s[i - j]:
cnt += 1
result_tmp += s[i + j]
else:
if(cnt*2-1 > max_len):
max_len = cnt*2-1
result = result_tmp[::-1][:-1] + result_tmp
break
# for even substring
for i in range(len(s)):
cnt = 0
result_tmp = ''
for j in range(i + 2):
if j == 0:
continue
if j <= i and i + j - 1 < len(s) and s[i + j - 1] == s[i - j]:
cnt += 1
result_tmp += s[i - j]
else:
if(cnt*2 > max_len):
max_len = cnt*2
result = result_tmp[::-1] + result_tmp
break
return result