Leetcode-5 最长回文子串
原题链接 https://leetcode-cn.com/problems/longest-palindromic-substring/
1 2
| func longestPalindrome(s string) string { }
|
题解
递归版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| func longestPalindrome(s string) string { if len(s) <= 1 { return s } s1 := longestPalindrome(s[1:])
right := len(s) for ; right > 0; right-- { if isOk(s[:right]) { break } } s2 := s[:right]
if len(s1) > len(s2) { return s1 } return s2 }
func isOk(s string) bool { if len(s) <= 1 { return true } start, end := 0, len(s)-1 for start < end { if s[start] != s[end] { return false } start++ end-- } return true }
|
非递归版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| func longestPalindrome(s string) string { length := len(s) if length <= 1 { return s }
begin, maxLen := 0, 1 var dp = make([][]bool, length) for k1 := range dp { dp[k1] = make([]bool, length) for k2 := range dp[k1] { dp[k1][k2] = false } dp[k1][k1] = true }
for size := 2; size <= length; size++ { founded := false for start := 0; start <= length-size; start++ { end := start + size - 1 if s[start] == s[end] { if size == 2 || dp[start+1][end-1] { dp[start][end] = true if !founded && size > maxLen { maxLen, begin = size, start founded = true } } } } } return s[begin : begin+maxLen] }
|
Github: https://github.com/Junedayday/code_reading
Blog: http://junes.tech/
Bilibili: https://space.bilibili.com/293775192
公众号: golangcoding