File tree Expand file tree Collapse file tree 1 file changed +37
-12
lines changed Expand file tree Collapse file tree 1 file changed +37
-12
lines changed Original file line number Diff line number Diff line change 1
- ## 题目地址
1
+ ## 题目地址(5. 最长回文子串)
2
2
3
- https://leetcode.com/problems/longest-palindromic-substring/description /
3
+ https://leetcode-cn .com/problems/longest-palindromic-substring/
4
4
5
5
## 题目描述
6
6
7
- ```
8
- Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
7
+ 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
9
8
10
- Example 1:
9
+ 示例 1:
11
10
12
- Input : "babad"
13
- Output : "bab"
14
- Note : "aba" is also a valid answer.
15
- Example 2:
11
+ 输入 : "babad"
12
+ 输出 : "bab"
13
+ 注意 : "aba" 也是一个有效答案。
14
+ 示例 2:
16
15
17
- Input: "cbbd"
18
- Output: "bb"
19
- ```
16
+ 输入: "cbbd"
17
+ 输出: "bb"
20
18
21
19
## 思路
22
20
@@ -51,6 +49,33 @@ base case就是一个字符(轴对称点是本身),或者两个字符(
51
49
52
50
## 代码
53
51
52
+ 代码支持:Python,JavaScript:
53
+
54
+ Python Code:
55
+
56
+ ``` python
57
+ class Solution :
58
+ def longestPalindrome (self , s : str ) -> str :
59
+ n = len (s)
60
+ if n == 0 :
61
+ return " "
62
+ res = s[0 ]
63
+ def extend (i , j , s ):
64
+ while (i >= 0 and j < len (s) and s[i] == s[j]):
65
+ i -= 1
66
+ j += 1
67
+ return s[i + 1 :j]
68
+
69
+ for i in range (n - 1 ):
70
+ e1 = extend(i, i, s)
71
+ e2 = extend(i, i + 1 , s)
72
+ if max (len (e1), len (e2)) > len (res):
73
+ res = e1 if len (e1) > len (e2) else e2
74
+ return res
75
+ ```
76
+
77
+ JavaScript Code:
78
+
54
79
``` js
55
80
/*
56
81
* @lc app=leetcode id=5 lang=javascript
You can’t perform that action at this time.
0 commit comments