sourcecode

Monday, December 3, 2012

Longest Palindromic Substring


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 {//passed large test
public:
    string longestPalindrome(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        map<int, int> record;
        int maxLength = 0;
        for(int palii = 0; palii < s.size(); ++palii){//start from the center of a palindrome
            int matchCount = 0, jj = 0;
            while(palii+jj < s.size() && palii-jj >=0 && s[palii+jj] == s[palii-jj]){//odd case
                ++jj;
            }
            if (maxLength < jj*2-1){
                maxLength = jj*2-1;
                record[maxLength] = palii;
            }            

            matchCount = 0, jj = 0;
            while(palii+jj+1 < s.size() && palii-jj >=0 && s[palii+jj+1] == s[palii-jj]){//even case
                ++jj;
            }
            if (maxLength < jj*2){
                maxLength = jj*2;
                record[maxLength] = palii;
            }            
        }//for palii
        int const centerIndex = record.rbegin()->second;
        int const startIndex = centerIndex-maxLength/2+!(maxLength%2);
        return s.substr(startIndex, maxLength);
    }//()
};

No comments: