Skip to content

Commit be465bf

Browse files
authored
feat: Add Python Code
1 parent db60a45 commit be465bf

File tree

1 file changed

+37
-12
lines changed

1 file changed

+37
-12
lines changed

problems/5.longest-palindromic-substring.md

Lines changed: 37 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,20 @@
1-
## 题目地址
1+
## 题目地址(5. 最长回文子串)
22

3-
https://leetcode.com/problems/longest-palindromic-substring/description/
3+
https://leetcode-cn.com/problems/longest-palindromic-substring/
44

55
## 题目描述
66

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。
98

10-
Example 1:
9+
示例 1:
1110

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:
1615

17-
Input: "cbbd"
18-
Output: "bb"
19-
```
16+
输入: "cbbd"
17+
输出: "bb"
2018

2119
## 思路
2220

@@ -51,6 +49,33 @@ base case就是一个字符(轴对称点是本身),或者两个字符(
5149

5250
## 代码
5351

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+
5479
```js
5580
/*
5681
* @lc app=leetcode id=5 lang=javascript

0 commit comments

Comments
 (0)