Monday, November 25, 2013

LeetCode Problem : Longest Palindromic Substring

Problem

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.

Code

string longestPalindrome(string s) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    int n  =s.size();
    if(n == 0)
        return s;
    vector<vector<bool> > p(n,vector<bool>(n,false));
    int maxlen = 1;
    int start_index = 0;
    for(int i = 0;i < n;++i)
        p[i][0] = true;
    for(int i = 0;i < n - 1;++i){
        if(s[i] == s[i+1]){
            p[i][1] = true;
            maxlen = 2;
            start_index = i;
        }
    }
    for(int len = 3;len <= n;++len){
        for(int i = 0;i <= n - len;++i){
            if(p[i+1][len-3] && s[i] == s[i + len - 1]){
                p[i][len - 1] = true;
                maxlen = len;
                start_index = i;
            }
        }
    }
    return s.substr(start_index,maxlen);
}

No comments:

Post a Comment