Golang最长回文子串

题目

Golang 实现,给定一个 字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

示例1

输入: "babad" 输出: "bab" 注意: "aba" 也是一个有效答案。

示例2

输入: "cbbd" 输出: "bb"

代码具体实现

package main import ( "fmt" ) func longestPalindrome(s string) string { res := "" window := 1 for i := 0; i < len(s); i++ { for j := i + window; j <= len(s); j++ { temp := s[i : j] if IsPalindrome(temp) { res = temp window = len(temp) } } } return res } func IsPalindrome(s string) bool { front, back := 0, len(s)-1 for front < back { if s[front] != s[back] { return false } front++ back-- } return true } func main() { fmt.Println("嗨客网(www.haicoder.net)") fmt.Println(longestPalindrome("babad")) fmt.Println(longestPalindrome("cbbd")) }

程序运行后,控制台输出如下:

05_golang最长子串回文.png

输入了两组测试用例,得出了正确答案。