LeetCode 5. Longest Palindromic Substring(medium难度)

Posted 皇家大鹏鹏

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 5. Longest Palindromic Substring(medium难度)相关的知识,希望对你有一定的参考价值。

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

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

 

Example:

Input: "cbbd"

Output: "bb"


这道题很经典,求最长回文子串并且返回它,暴力搜索法复杂度O(n^3),最后会超时,比较经典的解法是从某个字符开始,然后向两边开开始检索回文串
这样做的复杂度是O(N^2),面试是能写出这样的代码其实已经很不错了,代码如下:
 1 class Solution {
 2 public:
 3     string longestPalindrome(string s) 
 4     {
 5         int  start = 0, end = 0;
 6         for (int i = 0; i < s.length(); i++)
 7         {
 8             int len1 = expandAroundCenter(s,i,i);
 9             int len2 = expandAroundCenter(s,i,i+1);
10             int len = max(len1,len2);  //被自己的蠢哭 这里之前居然写成了max(len,len1),居然能通过一些测试用例
11             if (len > end - start + 1) //是否加一无所谓,唯一的区别在于是否需要考虑与当前最长字符串等长的字符串
12             {
13                 start = i - (len - 1) / 2;
14                 end = i + len / 2;
15             }
16         }
17         return s.substr(start, end - start + 1);
18         
19     }
20     
21     int expandAroundCenter(string s, int left, int right)
22     {
23         int L = left, R = right;
24         while (L >= 0 && R < s.length() && s[L]== s[R])
25         {
26             L--;
27             R++;
28         }
29         return R - L - 1;//这里为啥要减一,我的理解是模拟一个开区间,只计算区间内的数字数量而不包含端点
30     }
31 };

当然还有更逆天的算法,来自discuss的大神,可以达到O(N)的复杂度,代码如下:

 1 class Solution {
 2 public:
 3     string longestPalindrome(string s) {
 4         //拷贝牛人快速解法
 5         int n = s.size(), len = 0, start = 0;
 6         for(int i = 0; i < n; i++){
 7             int left = i, right = i;
 8             while(right < n && s[right+1] == s[right]) right++;
 9             i = right;
10             while(left > 0 && right < n-1 && s[left-1] == s[right+1]){
11                 left--;
12                 right++;
13             }
14             
15             if(len < right-left+1){
16                 len = right - left + 1;
17                 start = left;
18             }
19         }
20         return s.substr(start, len);
21     }
22 };

比较经典的解法应该是“马拉车算法”,但是不是很好理解,详情请参考https://www.cnblogs.com/grandyang/p/4475985.html

https://articles.leetcode.com/longest-palindromic-substring-part-ii/

 








以上是关于LeetCode 5. Longest Palindromic Substring(medium难度)的主要内容,如果未能解决你的问题,请参考以下文章

leetcode--5. Longest Palindromic Substring

#Leetcode# 5. Longest Palindromic Substring

LeetCode题解 #5 Longest Palindromic Substring

[LeetCode] 5 Longest Palindromic Substring

Leetcode #5. Longest Palindromic Substring

LeetCode 5_Longest Palindromic Substring