5. Longest Palindromic Substring(middle)

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"

求最长回文字符串,容易理解,但是复杂性较高,先摘下代码,之后有改进继续更新

class Solution {
public:
    string longestPalindrome(string s) {
        
        int start=0;
        int longlen=1;
        int len = s.size();
        if(len<=1){
            return s;
        }
        
        for(int j=0;j<len-1;j++){
            if(s[j]==s[j+1]){
                
                start=j;
                longlen=2;
            }
        }
        int klen=3;
        while(klen<=len){// 从长度为3开始遍历
            for(int k=0;k<len-klen+1;k++){
                int begin=k;int back=k+klen-1;//记录下字符串的开头和结尾
                while(begin<back){
                    if(s[begin]!=s[back]) break;
                    else 
                        begin++;
                        back--;
                }
                if(begin>=back){
                    
                    start=k;
                    longlen=klen;
                    break;
               
                }
            
                
            }
            klen++;
        }
        return s.substr(start,longlen);
    }
};
点赞