Saturday, April 18, 2015

[LeetCode] 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) {
        int len = s.size();
        bool rec[len][len];;
        
        int max = 0;
        int l = 0, r = 0;
        
        for(int i=0;i<len;i++)
        {
            for(int j=0;j<i;j++)
            {
                rec[j][i] = s[j] == s[i] && 
                      ( i - j < 2 || rec[j+1][i-1]);
                if(rec[j][i] && i - j > max)
                {
                    max = i-j;
                    l = j;
                    r = i;
                }
            }
            rec[i][i] = 1;
        }
        return s.substr(l,r-l+1);
    }
};