1
1
public class ManacherAlgorithm {
2
+
3
+ // Preprocesses the input string by adding boundary characters
2
4
private String preprocess (String s ) {
3
5
StringBuilder sb = new StringBuilder ();
4
- sb .append ('^' );
6
+ sb .append ('^' ); // Add starting boundary
5
7
for (int i = 0 ; i < s .length (); i ++) {
6
- sb .append ('#' );
8
+ sb .append ('#' ); // Add boundary between characters
7
9
sb .append (s .charAt (i ));
8
10
}
9
- sb .append ("#$" );
11
+ sb .append ("#$" ); // Add ending boundary
10
12
return sb .toString ();
11
13
}
14
+
15
+ // Manacher's Algorithm to find the longest palindromic substring
12
16
public String longestPalindrome (String s ) {
13
17
String T = preprocess (s );
14
18
int n = T .length ();
15
- int [] P = new int [n ];
16
- int C = 0 , R = 0 ;
19
+ int [] P = new int [n ]; // Array to store the lengths of palindromes
20
+ int C = 0 , R = 0 ; // C is the center, R is the right boundary
21
+
22
+ // Iterate through the transformed string
17
23
for (int i = 1 ; i < n - 1 ; i ++) {
18
- int mirror = 2 * C - i ;
24
+ int mirror = 2 * C - i ; // Mirror of i with respect to the center C
25
+
26
+ // Use previously computed values or set P[i] to 0
19
27
P [i ] = (R > i ) ? Math .min (R - i , P [mirror ]) : 0 ;
28
+
29
+ // Expand around i
20
30
while (T .charAt (i + 1 + P [i ]) == T .charAt (i - 1 - P [i ])) {
21
31
P [i ]++;
22
- }
32
+ }
33
+
34
+ // Update center and right boundary if the palindrome expands beyond R
23
35
if (i + P [i ] > R ) {
24
36
C = i ;
25
37
R = i + P [i ];
26
38
}
27
39
}
40
+
41
+ // Find the longest palindrome in P
28
42
int maxLen = 0 ;
29
43
int centerIndex = 0 ;
30
44
for (int i = 1 ; i < n - 1 ; i ++) {
@@ -33,13 +47,10 @@ public String longestPalindrome(String s) {
33
47
centerIndex = i ;
34
48
}
35
49
}
50
+
51
+ // Calculate the starting index of the longest palindromic substring
36
52
int start = (centerIndex - maxLen ) / 2 ;
37
53
return s .substring (start , start + maxLen );
38
54
}
39
-
40
- public static void main (String [] args ) {
41
- ManacherAlgorithm ma = new ManacherAlgorithm ();
42
- String input = "babad" ;
43
- System .out .println ("Longest Palindromic Substring: " + ma .longestPalindrome (input ));
44
- }
45
55
}
56
+
0 commit comments