longest palindromic substring

这道题第一遍的时候不知道为何没有做出来。

第二次做的基本思路是这样的,分成两种情况,single center和double center分别进行loop,然后AC了

解法1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class (object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
max_length = 0
max_str = ""
for i in range(len(s)):
left = i
right = i
while left >= 0 and right <= len(s) - 1 and s[left] == s[right]:
left -= 1
right += 1
if right - left - 1 > max_length:
max_length = right - left - 1
max_str = s[left+1:right]
# case 2 double center
if i + 1 < len(s) and s[i] == s[i+1]:
left = i
right = i + 1
while left >= 0 and right <= len(s) - 1 and s[left] == s[right]:
left -= 1
right += 1
if right - left - 1 > max_length:
max_length = right - left - 1
max_str = s[left+1:right]
return max_str

仔细的阅读了一下leetcode上的解法发现时间复杂度和空间复杂度和我上面的算法一样,所以这道题就算事过了。

加强解法
http://articles.leetcode.com/longest-palindromic-substring-part-ii/