File tree 1 file changed +45
-0
lines changed
src/main/java/com/thealgorithms/strings
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class ManacherAlgorithm {
2
+ private String preprocess (String s ) {
3
+ StringBuilder sb = new StringBuilder ();
4
+ sb .append ('^' );
5
+ for (int i = 0 ; i < s .length (); i ++) {
6
+ sb .append ('#' );
7
+ sb .append (s .charAt (i ));
8
+ }
9
+ sb .append ("#$" );
10
+ return sb .toString ();
11
+ }
12
+ public String longestPalindrome (String s ) {
13
+ String T = preprocess (s );
14
+ int n = T .length ();
15
+ int [] P = new int [n ];
16
+ int C = 0 , R = 0 ;
17
+ for (int i = 1 ; i < n - 1 ; i ++) {
18
+ int mirror = 2 * C - i ;
19
+ P [i ] = (R > i ) ? Math .min (R - i , P [mirror ]) : 0 ;
20
+ while (T .charAt (i + 1 + P [i ]) == T .charAt (i - 1 - P [i ])) {
21
+ P [i ]++;
22
+ }
23
+ if (i + P [i ] > R ) {
24
+ C = i ;
25
+ R = i + P [i ];
26
+ }
27
+ }
28
+ int maxLen = 0 ;
29
+ int centerIndex = 0 ;
30
+ for (int i = 1 ; i < n - 1 ; i ++) {
31
+ if (P [i ] > maxLen ) {
32
+ maxLen = P [i ];
33
+ centerIndex = i ;
34
+ }
35
+ }
36
+ int start = (centerIndex - maxLen ) / 2 ;
37
+ return s .substring (start , start + maxLen );
38
+ }
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
+ }
You can’t perform that action at this time.
0 commit comments