Description

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

Example

Example1:
    Input: "babad"

    Output: "bab"

    Note: "aba" is also a valid answer.
    
Example2:
    Input: "cbbd"

    Output: "bb"

思路

  • 最简单的思路,把所有的回文串都检查一遍,然后保存最长的
  • 怎么检查呢?
  • 回文串都是有一个对称中心的,所以现在,假设index=0为回文串的中心,然后向它的前和后扩展。这样遍历一遍可得到全部回文串。
  • 注意是相同字符的情况,如果字符连续相同,则不管它是出现奇数次还是偶数次都是回文的。
  • 注意判断边界条件

代码

  • 时间复杂度 O(n) ? O(n^2) ? 我还真不知道。。
class Solution {
public:
    string longestPalindrome(string s) {
        int len = s.size();
        
        if(len <= 1) return s;
        
        string res;
        int max_size = -1, max_start = 0, i = 0, j = 0;
        int index = 0, size = 0;
        while(index < len){
            i = index;
            while(index + 1 < len){
                if(s[index] == s[index + 1])
                    index++;
                else break;
            }
            
            j = index;
            while(i - 1 >= 0 && j + 1 < len){
                if(s[i - 1] == s[j + 1]){
                    i--;
                    j++;
                }
                else break;
            }
            
            size = j - i + 1;
            
            if(size > max_size){
                max_size = size;
                max_start = i;
            }
            
            index++;
        }
        
        res = s.substr(max_start, max_size);
        
        return res;
    }
};
内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程