-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongestPalindromicSubstring.java
55 lines (41 loc) · 1.33 KB
/
LongestPalindromicSubstring.java
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
49
50
51
52
53
54
55
class Solution {
public String longestPalindrome(String s) {
char[] T = new char[s.length()*2+3];
T[0]='$';
T[s.length()*2+2]='@';
for(int i = 0 ; i < s.length();i++)
{
T[2*i+1]='#';
T[2*i+2]=s.charAt(i);
}
T[s.length()*2+1]='#';
//T is ready now
int C=0, R=0;
int[] P = new int[T.length];
for(int i =1;i<T.length-1;i++)
{
int mirr= (2*C)-i;
//check if pseudo center i is within R
if(i<R)
P[i]= Math.min(P[mirr],R-i);
//expand to check and test for palindromes
while(T[i+P[i]+1] == T[i-P[i]-1])
P[i]++;
//check to see is Right boundary is violated by P of i
if((i+P[i])>R)
{
C=i;
R=i+P[i];
}
}
int length = 0;
int center = 0;
for (int i = 1; i < P.length-1; i++) {
if (P[i] > length) {
length = P[i];
center = i;
}
}
return s.substring((center - 1 - length) / 2, (center - 1 + length) / 2);
}
}