File tree 1 file changed +41
-0
lines changed
1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ """
3
+ 5. 最长回文子串
4
+ https://leetcode-cn.com/problems/longest-palindromic-substring/
5
+ 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
6
+ """
7
+ def longestPalindrome (self , s : str ) -> str :
8
+ l = len (s )
9
+ if l < 2 :
10
+ return s
11
+
12
+ # 定义状态方程,dp[i][j] 表示 i 到 j 是否是回文串
13
+ dp = [[False ] * l for _ in range (l )]
14
+
15
+ max_len = 1
16
+ start = 0
17
+
18
+ # i 到 i 必然是 True
19
+ for i in range (l ):
20
+ dp [i ][i ] = True
21
+
22
+ for j in range (1 , l ):
23
+ for i in range (0 , j ):
24
+ # 状态转移方程
25
+ if s [i ] == s [j ]:
26
+ if j - i < 3 :
27
+ dp [i ][j ] = True
28
+ else :
29
+ dp [i ][j ] = dp [i + 1 ][j - 1 ]
30
+ else :
31
+ dp [i ][j ] = False
32
+ # 记录开始位置,以及最大长度
33
+ if dp [i ][j ] and (j - i + 1 ) > max_len :
34
+ max_len = j - i + 1
35
+ start = i
36
+
37
+ return s [start : start + max_len ]
38
+
39
+
40
+ so = Solution ()
41
+ print (so .longestPalindrome ('cbbd' ))
You can’t perform that action at this time.
0 commit comments