对给定的字符串,要求输出最长对称子串的长度
时间: 2024-04-30 21:22:18 浏览: 12
好的,这个问题可以回答。最长对称子串可以通过中心扩展法来解决。具体实现可以参考以下代码:
```python
def longest_palindrome(string):
if len(string) == 0:
return 0
max_len = 1
for i in range(len(string)):
# 以当前字符为中心扩展子串
left, right = i, i
while left >= 0 and right < len(string) and string[left] == string[right]:
if right - left + 1 > max_len:
max_len = right - left + 1
left -= 1
right += 1
# 以当前字符和下一个字符的中心扩展子串
left, right = i, i+1
while left >= 0 and right < len(string) and string[left] == string[right]:
if right - left + 1 > max_len:
max_len = right - left + 1
left -= 1
right += 1
return max_len
```
其中,第一个while循环处理以当前字符为中心的对称子串,第二个while循环处理以当前字符和下一个字符为中心的对称子串。时间复杂度为O(n^2),空间复杂度为O(1)。