LongestPalindromicSubstring returns the longest palindromic substring in the input string
(s string)
| 8 | |
| 9 | // LongestPalindromicSubstring returns the longest palindromic substring in the input string |
| 10 | func LongestPalindromicSubstring(s string) string { |
| 11 | n := len(s) |
| 12 | if n == 0 { |
| 13 | return "" |
| 14 | } |
| 15 | |
| 16 | dp := make([][]bool, n) |
| 17 | for i := range dp { |
| 18 | dp[i] = make([]bool, n) |
| 19 | } |
| 20 | |
| 21 | start := 0 |
| 22 | maxLength := 1 |
| 23 | for i := 0; i < n; i++ { |
| 24 | dp[i][i] = true |
| 25 | } |
| 26 | |
| 27 | for length := 2; length <= n; length++ { |
| 28 | for i := 0; i < n-length+1; i++ { |
| 29 | j := i + length - 1 |
| 30 | if length == 2 { |
| 31 | dp[i][j] = (s[i] == s[j]) |
| 32 | } else { |
| 33 | dp[i][j] = (s[i] == s[j]) && dp[i+1][j-1] |
| 34 | } |
| 35 | |
| 36 | if dp[i][j] && length > maxLength { |
| 37 | maxLength = length |
| 38 | start = i |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | return s[start : start+maxLength] |
| 43 | } |
no outgoing calls