Leetcode 链接
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb"
找出最长回文子串
type Result struct{ pos, length int } func longestPalindrome(s string) string { res := Result{ pos : 0, length : 0, } str := "#" for _, v := range s { str += string(v) + "#" } tmpRune := []rune(str) for i:=0; i< len(str); i++ { tmpLen := check(tmpRune, i) if tmpLen > res.length { res.length = tmpLen res.pos = i } } resStr := str[res.pos - res.length : res.pos + res.length + 1] return strings.Replace(resStr, "#", "", -1) } func check(tmp []rune , pos int) int{ length := 0 from := pos-1 to := pos+1 for from>=0 && to<len(tmp) && tmp[from] == tmp[to] { length += 1 from-- to++ } return length }
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8