1
+ // Longest palindromic substring
2
+ // Manacher's algorithm
3
+
4
+ import java .util .Arrays ;
5
+
6
+ class LPS {
7
+
8
+ static void printSubStr (String str , int low , int high ) {
9
+ System .out .println (str .substring (low , high + 1 ));
10
+ }
11
+
12
+ public static void main (String [] args ) {
13
+ String str = "abcdcbaf" ;
14
+ System .out .println ("Length is: " +
15
+ longestPalSubstr (str ));
16
+ }
17
+
18
+ // input string
19
+ static int longestPalSubstr (String str ){
20
+
21
+ // Get the length
22
+ int n = str .length ();
23
+
24
+ // make a table of length * length
25
+ boolean table [][] = new boolean [n ][n ];
26
+
27
+ // single letter is always palindrome
28
+ // Lol
29
+ // make max = 1
30
+ int maxLength = 1 ;
31
+
32
+ // and fill the diagonals as 1 as true
33
+ for (int i = 0 ; i < n ; ++i )
34
+ table [i ][i ] = true ;
35
+
36
+
37
+ // for strings with length 2
38
+ int start = 0 ;
39
+
40
+ // go ot n-1
41
+ for (int i = 0 ; i < n -1 ; i ++){
42
+
43
+ // this and immidiate next
44
+ if (str .charAt (i ) == str .charAt (i +1 )){
45
+ // if matched make it true
46
+ // i and i+1
47
+ table [i ][i +1 ] = true ;
48
+
49
+ // this is palindrome and hence update the start and maxlength
50
+ start = i ;
51
+ maxLength = 2 ;
52
+ }
53
+ }
54
+
55
+
56
+ // Now for 3 and more
57
+ // we will use 1 and 2 data from table
58
+ for (int k = 3 ; k <= n ; k ++){
59
+ for (int i = 0 ; i < n -k +1 ; i ++){
60
+ int j = i + k - 1 ;
61
+ if (table [i +1 ][j -1 ] && str .charAt (i ) == str .charAt (j )){
62
+ table [i ][j ] = true ;
63
+
64
+ if (k > maxLength ){
65
+ start = i ;
66
+ maxLength = k ;
67
+ }
68
+ }
69
+ }
70
+ }
71
+
72
+ System .out .print ("Longest palindrome substring is; " );
73
+ printSubStr (str , start , start + maxLength - 1 );
74
+
75
+ return maxLength ; // return length of LPS
76
+
77
+ }
78
+
79
+ }
0 commit comments