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
function ShortestPalindrome ( s ) { let n = s . length ; let v = [ ] ; for ( let i = 0 ; i < n ; i ++ ) { let l = i ; let r = i ; let ans1 = " " ; let 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 . push ( ans1 ) ; v . push ( ans2 ) ; } let ans = v [ 0 ] ; for ( let i = 0 ; i < v . length ; i ++ ) { if ( v [ i ] != " " ) { if ( ans [ 0 ] >= v [ i ] [ 0 ] ) { ans = v [ i ] ; } } } return ans ; } let s = " " ; document . write ( ShortestPalindrome ( s ) ) ;