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, and there exists one unique longest palindromic substring.

class Solution {
public:
    string longestPalindrome(string s) {
        if(s.empty() || s.size() == 1)  return s;

        int start = 0, len = 1;

        //选取i为回文中心
        for(int i = 0; i < s.size();){
            if(s.size() - i <= len/2) break;

            int k = i, j = i;

            //跳过与s[i]重复的字符(回文中有连续重复的字符)
            while(k < s.size() - 1&& s[k+1] == s[k])    k++;

            i = k+1;

            while(k < s.size() - 1 && j > 0 && s[k +1] == s[j - 1]){
                k++;
                j--;
            }

            int new_len = k - j +1;
            if(new_len > len){
                len = new_len;
                start = j;
            }
        }
        return s.substr(start, len);
    }
};

results matching ""

    No results matching ""