Tuesday, February 4, 2014

Longest Palindromic Substring

http://www.geeksforgeeks.org/longest-palindromic-substring-set-2/



static String longestSubStr(String str)
{
int n = str.length();
if(n == 0 || n == 1)
{
return str;
}
int i , j = 0, k = 1, max = 0, start = 0, end = 0;

for (i = 1; i < n; i++)
{

k = i;
j = i-1;
while(k= 0 && str.charAt(j) == str.charAt(k))
{
j--; k++;
}
j = j+1;
k = k-1;
if((k-j) > max )
{
start = j;
end = k;
max = (k-j);
}
k = i+1;
j = i-1;
while (k=0 && str.charAt(j) == str.charAt(k))
{
j--; k++;
}

j = j+1;
k = k-1;
if((k-j) > max )
{
start = j;
end = k;
max = (k-j);
}
}
System.out.println("max length: "+ (max+1));
return str.substring(start, end+1);

}

No comments:

Post a Comment