Shortest Palindromic Substring | Java program to find the shortest palindromic substring ; Function return the shortest palindromic substring ; One by one consider every character as center point of even and length palindromes ; Find the longest odd length palindrome with center point as i ; Find the even length palindrome with center points as i - 1 and i . ; Smallest substring which is not empty ; Driver code
import java . util . * ; import java . io . * ; class GFG { public static String ShortestPalindrome ( String s ) { int n = s . length ( ) ; Vector < String > v = new Vector < String > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int l = i ; int r = i ; String ans1 = " " ; String ans2 = " " ; while ( l >= 0 && r < n && s . charAt ( l ) == s . charAt ( r ) ) { ans1 += s . charAt ( l ) ; l -- ; r ++ ; } l = i - 1 ; r = i ; while ( l >= 0 && r < n && s . charAt ( l ) == s . charAt ( r ) ) { ans2 += s . charAt ( l ) ; l -- ; r ++ ; } v . add ( ans1 ) ; v . add ( ans2 ) ; } String ans = v . get ( 0 ) ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( v . get ( i ) != " " ) { if ( ans . charAt ( 0 ) >= v . get ( i ) . charAt ( 0 ) ) { ans = v . get ( i ) ; } } } return ans ; } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; System . out . println ( ShortestPalindrome ( s ) ) ; } }