欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

最长回文串_LeetCode解析,第五题:最长回文子串

发布时间:2025/3/19 编程问答 43 豆豆
生活随笔 收集整理的这篇文章主要介绍了 最长回文串_LeetCode解析,第五题:最长回文子串 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

LeetCode第五题:最长回文子串

5:

英文题面:

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"Output: "bab"Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"Output: "bb"

中文题面:

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

示例 1:

输入: "babad"输出: "bab"注意: "aba" 也是一个有效答案。

示例 2:

输入: "cbbd"输出: "bb"

思路:

求回文子串,

最简单的思路是暴力搜索,检索所有的子串检查是不是回文串,这个时间复杂度为O(n^3)。

第二可以考虑中心扩展法,对字符串中每个字符考虑为回文串的中心,向两边扩张到最大,这里注意有两种回文串,一个是长度为奇数的回文串,中心为一个字符,长度为偶数的回文串,中心为2个相同的字符。这里时间复杂度是O(n^2)

第三:Manacher算法,时间复杂度为O(n)

实例给出第二种实现代码:

class Solution(object): def __init__(self): self.max_len = 0 self.start = -1 self.end = -1 def longestPalindrome(self, s): """ :type s: str :rtype: str """ for i in range(len(s)): self.find_str(i,i,s) self.find_str(i,i+1,s) return s[self.start:self.end+1] def find_str(self, left, right,s): while (left>=0 and right self.max_len: self.max_len = right - left - 1 self.start = left+1 self.end = right-1

总结

以上是生活随笔为你收集整理的最长回文串_LeetCode解析,第五题:最长回文子串的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。