string longestPalindrome(string s) {
int n = s.length();
if(n<=1)return s;
int v[2][n];
int longest = 1, lindex = 0;
for (int i = 0; i < n; i++)v[1][i] = 1;
for (int i = 0; i < n-1; i++)
if(s[i] == s[i+1]){
lindex = i;
longest = 2;
v[0][i] = 1;
}
else v[0][i] = 0;
for ( int l = 3; l <= n; l++)
{
for (int i = 0; i+l-1 < n; i++)
{
int j = i+l-1;
if(v[l&1][i+1] && s[i] == s[j]){
lindex = i;
longest = l;
v[l&1][i] = 1;
}
else
v[l&1][i] = 0;
}
}
return s.substr(lindex, longest);
}
Saturday, September 20, 2014
LeetCode: Longest Palindromic Substring
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment