编写一个函数longestPalindrome(),找到非空字符串s中最长回文子串
时间: 2024-05-14 10:14:00 浏览: 130
以下是Python 3中的longestPalindrome()函数的实现:
```python
def longestPalindrome(s: str) -> str:
n = len(s)
if n < 2:
return s
# 初始化dp数组,dp[i][j]表示s[i:j+1]是否为回文子串
dp = [[False] * n for _ in range(n)]
# 初始化单个字符和两个字符的回文子串
for i in range(n):
dp[i][i] = True
if i < n - 1 and s[i] == s[i + 1]:
dp[i][i + 1] = True
max_len = 1 # 最长回文子串的长度
start = 0 # 最长回文子串的起始位置
# 枚举子串长度
for l in range(2, n):
# 枚举子串起始位置
for i in range(n - l):
j = i + l
if s[i] == s[j] and dp[i + 1][j - 1]:
dp[i][j] = True
if l + 1 > max_len:
max_len = l + 1
start = i
return s[start:start + max_len]
```
该函数使用动态规划的方法,时间复杂度为O(n^2),空间复杂度为O(n^2)。在初始化单个字符和两个字符的回文子串后,枚举子串长度和子串起始位置,判断子串是否为回文子串。如果是,则更新最长回文子串的长度和起始位置。最后返回最长回文子串。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)