知识点:回文
LeetCode第五题:https://leetcode-cn.com/problems/longest-palindromic-substring/solution/
语言:GoLang
// 判断“以某个字符为中心的字符串”是不是回文
// 遍历字符串中,每个字符作为中心的情况,寻找每个情况下最长的字符,即为答案
func longestPalindrome(s string) string {
length := len(s)
if length < 2 {
return s
}
res := ""
for i := 0; i < length - 1; i++ {
res = maxLength(res, palindrome(s, i, i))
res = maxLength(res, palindrome(s, i, i + 1))
}
return res
}
func palindrome(s string, left int, right int) string {
length := len(s)
for 0 <= left && right < length {
if s[left] == s[right] {
left--
right++
}else {
break
}
}
return s[left + 1 : right]
}
func maxLength(s1 string, s2 string) string {
if len(s1) > len(s2) {
return s1
}
return s2
}
原文:https://www.cnblogs.com/cenyol/p/13212267.html