Shortest Palindromic Substring | C # 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
using System ; using System . Collections . Generic ; class GFG { static string ShortestPalindrome ( string s ) { int n = s . Length ; List < string > v = new List < string > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int l = i ; int r = i ; string ans1 = " " ; string ans2 = " " ; while ( l >= 0 && r < n && s [ l ] == s [ r ] ) { ans1 += s [ l ] ; l -- ; r ++ ; } l = i - 1 ; r = i ; while ( l >= 0 && r < n && s [ l ] == s [ r ] ) { ans2 += s [ l ] ; l -- ; r ++ ; } v . Add ( ans1 ) ; v . Add ( ans2 ) ; } string ans = v [ 0 ] ; for ( int i = 0 ; i < v . Count ; i ++ ) { if ( v [ i ] != " " ) { if ( ans [ 0 ] >= v [ i ] [ 0 ] ) { ans = v [ i ] ; } } } return ans ; } static public void Main ( ) { string s = " geeksforgeeks " ; Console . WriteLine ( ShortestPalindrome ( s ) ) ; } }