最长回文字符串

Longest Palindromic Substring

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(n3)

class Solution {
public:
    bool isPalindormic(string::const_iterator first, string::const_iterator last)
    {
        --last;
        while(first<last)
        {
            if(*(first++)!=*(last--))
                return false;
        }
        return true;
    }
    string longestPalindrome(string s) {
        for(int len = s.size();len>0;--len)
            for(int start = 0;start+len<=s.size();++start)
                if(isPalindormic(s.cbegin()+start,s.cbegin()+start+len))
                    return s.substr(start,len);
        return "";
    }
};

改进解法

思路即为确定每个对称轴从左从右expand

class Solution {
public:
    string longestPalindrome(string s) {
        if(s.size()<2)
            return s;
        int min_start = 0,max_len = 1,i = 0;
        while(i<s.size())
        {
            if(s.size()-i<=max_len/2)
                break;
            int j = i,k = i;
            while(k<s.size()-1&&s[k]==s[k+1])
                ++k; //解决偶数问题转变为奇数问题
            i = k + 1;//更新i
            while(k<s.size()-1&&j>0&&s[k+1]==s[j-1])
            {
                ++k;
                --j;
            }//expand
            int new_len = k-j+1;//更新len
            if(new_len>max_len)
            {
                max_len = new_len;
                min_start = j;
            }
        }
        return s.substr(min_start,max_len);
    }
};