longestPalindrome

This commit is contained in:
ehlxr 2022-06-04 14:34:28 +08:00
parent f588b88700
commit c6760f0a68
2 changed files with 51 additions and 12 deletions

30
main.go
View File

@ -1,22 +1,28 @@
package main
import (
"fmt"
. "github.com/ehlxr/leetcode-go/src"
)
func main() {
node5 := &ListNode{Val: 5, Next: nil}
node4 := &ListNode{Val: 4, Next: node5}
node3 := &ListNode{Val: 3, Next: node4}
node2 := &ListNode{Val: 2, Next: node3}
node1 := &ListNode{Val: 1, Next: node2}
root := &ListNode{Val: 0, Next: node1}
fmt.Printf("%v\n", root)
// node5 := &ListNode{Val: 5, Next: nil}
// node4 := &ListNode{Val: 4, Next: node5}
// node3 := &ListNode{Val: 3, Next: node4}
// node2 := &ListNode{Val: 2, Next: node3}
// node1 := &ListNode{Val: 1, Next: node2}
// root := &ListNode{Val: 0, Next: node1}
// fmt.Printf("%v\n", root)
//
// fmt.Printf("%v\n", Reverse(root))
fmt.Printf("%v\n", ReverseRec(root))
// fmt.Printf("%v\n", ReverseRec(root))
// fmt.Printf("%v\n", ReverseKGroup(root, 2))
// s := "Hello 你好"
// println(s[2], s[6])
// rs := []rune(s)
// println(string(rs[6]))
s := "babad"
println(LongestPalindrome(s))
}

33
src/palindrome.go Normal file
View File

@ -0,0 +1,33 @@
package src
/* 给你一个字符串 s找到 s 中最长的回文子串 */
func LongestPalindrome(s string) string {
var res string
for i := 0; i < len(s); i++ {
// 回文串长度为奇数
p1 := palindrome(s, i, i)
if len(p1) > len(res) {
res = p1
}
// 回文串长度为偶数
p2 := palindrome(s, i, i+1)
if len(p2) > len(res) {
res = p2
}
}
return res
}
// 从中心向两段扩展
func palindrome(s string, l, r int) string {
for l >= 0 && r < len(s) && s[l] == s[r] {
l--
r++
}
// (r-1)-l 为回文串的长度
// s[l+1 : (r-1)-l+(l+1)] 为回文串
return s[l+1 : r]
}