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+ // Longest Palindromic Substring
2+ import java .util .Scanner ;;
3+
4+
5+ class LongestPalindromicSubstring {
6+ public static void main (String [] args ) {
7+ Solution s = new Solution ();
8+ String str = "" ;
9+ Scanner sc = new Scanner (System .in );
10+ System .out .print ("Enter the string: " );
11+ str = sc .nextLine ();
12+ System .out .println ("Longest substring is : " +s .longestPalindrome (str ));
13+ }
14+ }
15+
16+ class Solution {
17+ public String longestPalindrome (String s ) {
18+ if (s == null || s .length () == 0 ) {
19+ return "" ;
20+ }
21+ int n = s .length ();
22+ String maxStr = "" ;
23+ for (int i = 0 ; i < n ; ++i ) {
24+ for (int j = i ; j < n ; ++j ) {
25+ if (isValid (s , i , j ) == true ) {
26+ if (j - i + 1 > maxStr .length ()) { // update maxStr
27+ maxStr = s .substring (i , j + 1 );
28+ }
29+ }
30+ }
31+ }
32+ return maxStr ;
33+ }
34+
35+ private boolean isValid (String s , int lo , int hi ) {
36+ int n = hi - lo + 1 ;
37+ for (int i = 0 ; i < n / 2 ; ++i ) {
38+ if (s .charAt (lo + i ) != s .charAt (hi - i )) {
39+ return false ;
40+ }
41+ }
42+ return true ;
43+ }
44+ }
You can’t perform that action at this time.
0 commit comments