Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
题目和第三题类似,求给定字符串中最大回文字符串。
第一次提交出现TLE(超时),后将第二层循环初始条件j:=i+1改为j:=i+len(output),既小于已知最长结果的字符串都不再检测,通过。
解法如下:
func longestPalindrome(s string) string {
var output []byte
bs := []byte(s)
if len(bs) > 0 {
output = bs[0:1]
}
for i := 0; i < len(bs); i++ {
for j := i + len(output); j < len(bs); j++ {
flag := 0
for k := 0; k < (j-i+1)/2; k++ {
if bs[k+i] != bs[j-k] {
flag = 1
break
}
}
if flag == 0 && j-i+1 > len(output) {
output = bs[i : j+1]
}
}
}
return string(output)
}
网友评论