题目
5. Longest Palindromic Substring
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"
我的代码
方法一:
func longestPalindrome(s string) string {
result := ""
for i := 0; i < len(s); i++ {
temp := longestPalindromeByMiddle(s, i)
if len(temp) > len(result) {
result = temp
}
temp = longestPalindromeByMiddle2(s, i)
if len(temp) > len(result) {
result = temp
}
}
return result
}
func longestPalindromeByMiddle2(s string, index int) string {
pre, next := index-1, index+1
length := 1
for true {
if pre < 0 || next >= len(s) {
break
}
if s[pre] == s[next] {
length = length + 2
pre--
next++
} else {
break
}
}
return s[pre+1 : length+pre+1]
}
func longestPalindromeByMiddle(s string, index int) string {
pre, next := index-1, index
length := 0
for true {
if pre < 0 || next >= len(s) {
break
}
if s[pre] == s[next] {
length = length + 2
pre--
next++
} else {
break
}
}
return s[pre+1 : length+pre+1]
}