lc-go/solutions/0/q5/solution.go
2026-01-07 18:04:39 +09:00

37 lines
681 B
Go

package q5
// Note: Although it can be done in O(N) with, e.g., Manacher's algorithm, the
// input size is small enough to brute-force.
func expand(s string, l, r int) (int, int) {
for l > 0 && r < len(s)-1 && s[l-1] == s[r+1] {
l--
r++
}
return l, r
}
func longestPalindrome(s string) string {
maxLen, mL, mR := 0, 0, 0
for c := range len(s) {
l, r := expand(s, c, c)
len_ := r - l + 1
if len_ > maxLen {
maxLen, mL, mR = len_, l, r
}
}
for c := range len(s) - 1 {
if s[c] == s[c+1] {
l, r := expand(s, c, c+1)
len_ := r - l + 1
if len_ > maxLen {
maxLen, mL, mR = len_, l, r
}
}
}
return s[mL : mR+1]
}
var _ = longestPalindrome