描述
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
分析
如果暴力搜索,对每一个位置都进行两边扩张,时间复杂度为O(n^2)
。进过观察发现判断从位置i
到j
之间的字符串是否为回文满足动态规划的最优子结构f(i, j) = (s[j] == s[i]) and (j - i < 2 or f(i + 1, j - 1))
。所以可以使用一个二维数组来缓存子问题结果,时间复杂度O(n^2)
,空间O(n^2)
。
目前最优的解法是Manacher算法,通过一个精妙的构造省去了大量冗余的搜索。对于长回文字符串时间可以降到O(n)
。
代码
暴力搜索
1 | class Solution(object): |
动态规划
在Leetcode上提交会超时1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
n = len(s)
# matrix to store if s[i:j+1] is palindrome
f = [[False] * n for i in xrange(n)]
max_len = 0
idx = -1
for j in xrange(n):
f[j][j] = True
for i in xrange(j):
f[i][j] = (s[j] == s[i]) and (j - i < 2 or f[i + 1][j - 1])
if f[i][j] and (j - i + 1) > max_len:
max_len = j - i + 1
idx = i
return s[idx: idx + max_len]
Manacher算法
1 | class Solution(object): |