-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path19. Longest Palindromic Substring-Manacher's Algorithm
More file actions
48 lines (38 loc) · 1.22 KB
/
19. Longest Palindromic Substring-Manacher's Algorithm
File metadata and controls
48 lines (38 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public String longestPalindrome(String s) {
int n=s.length();
char[] newStr=new char[2*n+1];
int i=0;
newStr[i++]='#';
for(char c:s.toCharArray()){
newStr[i++]=c;
newStr[i++]='#';
}
int p[]=new int[2*n+1];
int center=0,right=0;
int longestLength=0,longestCenter=0;
for(i=0;i<newStr.length;i++){
int mirror= 2*center-i;
if(right>i){
p[i]=Math.min(p[mirror],right-i);
}
int a=i + (p[i]+1);
int b=i - (p[i]+1);
while(b>=0 && a<newStr.length && newStr[a]==newStr[b]){
b--;
a++;
p[i]++;
}
if(p[i]>=longestLength){
longestCenter=i;
longestLength=p[i];
}
if(i+p[i]>right){
center=i;
right=i+p[i];
}
}
String st=new String(newStr);
return st.substring(longestCenter-longestLength,longestCenter+longestLength).replace("#","");
}
}