File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package test ;
2+
3+ import java .io .*;
4+ import java .util .*;
5+
6+ /*
7+ * Algorithm explanation https://leetcode.com/problems/longest-palindromic-substring/
8+ */
9+ public class LongestPalindromicSubstring {
10+ public static void main (String [] args ) {
11+ String a = "babad" ;
12+ String b = "cbbd" ;
13+
14+ String aLPS = LPS (a );
15+ String bLPS = LPS (b );
16+
17+ System .out .println (a + " => " + aLPS );
18+ System .out .println (b + " => " + bLPS );
19+ }
20+
21+ private static String LPS (String input ) {
22+ if (input == null || input .length () == 0 ){
23+ return input ;
24+ }
25+ boolean arr [][] = new boolean [input .length ()][input .length ()];
26+ int start = 0 , end = 0 ;
27+ for (int g = 0 ; g < input .length (); g ++) {
28+ for (int i = 0 , j = g ; j < input .length (); i ++, j ++) {
29+
30+ if (g == 0 ) {
31+ arr [i ][j ] = true ;
32+ } else if (g == 1 ) {
33+ if (input .charAt (i ) == input .charAt (j )) {
34+ arr [i ][j ] = true ;
35+ } else {
36+ arr [i ][j ] = false ;
37+ }
38+ } else {
39+
40+ if (input .charAt (i ) == input .charAt (j ) && arr [i + 1 ][j - 1 ]) {
41+ arr [i ][j ] = true ;
42+ } else {
43+ arr [i ][j ] = false ;
44+ }
45+ }
46+
47+ if (arr [i ][j ]) {
48+ start = i ;
49+ end = j ;
50+ }
51+ }
52+ }
53+ return input .substring (start , end + 1 );
54+ }
55+
56+ }
You can’t perform that action at this time.
0 commit comments