go语言解leetcode习题 5. Longest Palindromic Substring
程序员文章站
2022-03-15 22:25:59
...
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)
}
上一篇: 简单理解和实现socket(套接字)
下一篇: const,#define