8000 5.Longest Palindromic Substring · snowshawn/LeetCode@e704285 · GitHub
[go: up one dir, main page]

Skip to content

Commit e704285

Browse files
committed
5.Longest Palindromic Substring
1 parent e8a36f3 commit e704285

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# 题目
2+
给定一个字符串s,找到最长回文子字符串s。假设s的最大长度为s。
3+
4+
**举例1:**
5+
6+
```
7+
输入:"babad"
8+
输出:"bab"
9+
注意:"aba"也是一个有效结果。
10+
```
11+
12+
**举例2:**
13+
14+
```
15+
输入:"cbbd"
16+
输出:"bb"
17+
```
18+
19+
# 思路
20+
21+
可以使用中心扩展的方法,把给定的每一个字母当做中心,向两边扩展,这样找到最长的子回文串。算法复杂度为O(N^2)。
22+
分为两种情况:
23+
24+
- aba,这样长度为奇数的回文
25+
- abba,这样长度为偶数的回文
26+
27+
# 代码
28+
基本方法:
29+
30+
``` python
31+
class Solution(object):
32+
def longestPalindrome(self, s):
33+
"""
34+
:type s: str
35+
:rtype: str
36+
"""
37+
length = len(s)
38+
maxlength = 1
39+
start = 0
40+
if length == 0: return None
41+
if length == 1: return True
42+
43+
#奇数回文
44+
for i in range(length):
45+
j = i - 1
46+
k = i + 1
47+
while j >= 0 and k < length and s[j] == s[k]:
48+
if k - j + 1 > maxlength:
49+
maxlength = k - j + 1
50+
start = j
51+
j -= 1
52+
k += 1
53+
54+
#偶数回文
55+
for i in range(length):
56+
j = i
57+
k = i + 1
58+
while j >= 0 and k < length and s[j] == s[k]:
59+
if k - j + 1 > maxlength:
60+
maxlength = k - j + 1
61+
start = j
62+
j -= 1
63+
k += 1
64+
65+
if maxlength > 0:
66+
return s[start:start+maxlength]
67+
return None
68+
```
69+
70+
改进方法:
71+
72+
``` python
73+
class Solution(object):
74+
def longestPalindrome(self, s):
75+
"""
76+
:type s: str
77+
:rtype: str
78+
"""
79+
if len(s)==0:
80+
return 0
81+
maxLen=1
82+
start=0
83+
for i in range(len(s)):
84+
if i-maxLen >=1 and s[i-maxLen-1:i+1]==s[i-maxLen-1:i+1][::-1]:
85+
start=i-maxLen-1
86+
maxLen+=2
87+
continue
88+
89+
if i-maxLen >=0 and s[i-maxLen:i+1]==s[i-maxLen:i+1][::-1]:
90+
start=i-maxLen
91+
maxLen+=1
92+
return s[start:start+maxLen]
93+
```
94+
95+

0 commit comments

Comments
 (0)
0