Wednesday, February 20, 2013
[LeetCode] Longest PalinDromic Substring
Thought:
It is not difficult to come up with the idea to populate every character and expand along its two sides. This method will get a O(n^2) time complexity.
There surprisingly exists a very nontrivial algorithm here whose time complexity is O(n)! Manacher’s Algorithm
Code:
public class Solution {
public String longestPalindrome(String s) {
String input = preProcess(s);
int len = input.length();
int[] P = new int[len];
int center = 0, right = 0;
for( int i = 1; i < len - 1; i++ ){
int j = 2 * center - i;
P[i] = right > i? Math.min( right - i, P[j] ): 0;
while( input.charAt(i + P[i] + 1) == input.charAt(i - P[i] - 1) ){
P[i]++;
}
if( i + P[i] > right){
right = i + P[i];
center = i;
}
}
int resultc = 0, resultl = 0;
for( int i = 0 ; i < len; i++ ){
if(P[i]>resultl){
resultc = i;
resultl = P[i];
}
}
return s.substring( (resultc - resultl - 1)/2, (resultc + resultl)/2 - 0 );
}
public String preProcess(String s){
String temp = "!#";
for( int i = 0; i < s.length(); i++ ){
temp = temp + s.substring(i, i + 1);
temp = temp + "#";
}
temp = temp + "@";
return temp;
}
}
Labels:
LeetCode
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment