1
1
package com .thealgorithms .strings ;
2
2
3
- // Longest Palindromic Substring
4
3
import java .util .Scanner ;
5
4
6
5
final class LongestPalindromicSubstring {
@@ -9,42 +8,39 @@ private LongestPalindromicSubstring() {
9
8
10
9
public static void main (String [] args ) {
11
10
Solution s = new Solution ();
12
- String str = "" ;
13
11
Scanner sc = new Scanner (System .in );
14
12
System .out .print ("Enter the string: " );
15
- str = sc .nextLine ();
16
- System .out .println ("Longest substring is : " + s .longestPalindrome (str ));
13
+ String str = sc .nextLine ();
14
+ System .out .println ("Longest palindromic substring is: " + s .longestPalindrome (str ));
17
15
sc .close ();
18
16
}
19
17
}
20
18
21
19
class Solution {
20
+ int left = 0 , right = -1 , maxSize = 0 ;
22
21
23
22
public String longestPalindrome (String s ) {
24
- if (s == null || s .length () == 0 ) {
25
- return "" ;
23
+ for (int i = 0 ; i < s .length (); i ++) {
24
+ f (s , i , i ); // Odd length palindromes
25
+ f (s , i , i + 1 ); // Even length palindromes
26
26
}
27
- int n = s .length ();
28
- String maxStr = "" ;
29
- for (int i = 0 ; i < n ; ++i ) {
30
- for (int j = i ; j < n ; ++j ) {
31
- if (isValid (s , i , j )) {
32
- if (j - i + 1 > maxStr .length ()) { // update maxStr
33
- maxStr = s .substring (i , j + 1 );
34
- }
35
- }
36
- }
37
- }
38
- return maxStr ;
27
+ return s .substring (left , right + 1 );
39
28
}
40
29
41
- private boolean isValid (String s , int lo , int hi ) {
42
- int n = hi - lo + 1 ;
43
- for (int i = 0 ; i < n / 2 ; ++i ) {
44
- if (s .charAt (lo + i ) != s .charAt (hi - i )) {
45
- return false ;
30
+ public void f (String s , int l , int r ) {
31
+ while (l >= 0 && r < s .length ()) {
32
+ if (s .charAt (l ) == s .charAt (r )) {
33
+ l --;
34
+ r ++;
35
+ } else {
36
+ break ;
46
37
}
47
38
}
48
- return true ;
39
+ int size = r - l - 1 ;
40
+ if (maxSize < size ) {
41
+ left = l + 1 ;
42
+ right = r - 1 ;
43
+ maxSize = size ;
44
+ }
49
45
}
50
46
}
0 commit comments