Skip to content

Instantly share code, notes, and snippets.

@Skarlso
Created March 6, 2020 16:10
Show Gist options
  • Save Skarlso/78a6c1ecd62357c2ef32178962b963be to your computer and use it in GitHub Desktop.
Save Skarlso/78a6c1ecd62357c2ef32178962b963be to your computer and use it in GitHub Desktop.
Longest palindrome in string using Go
func longestPalindrome(s string) string {
if len(s) < 1 {
return ""
}
start := 0
end := 0
for i := 0; i < len(s); i++ {
len1 := expandAroundCenter(s, i, i)
len2 := expandAroundCenter(s, i, i+1)
len := int(math.Max(float64(len1), float64(len2)))
if len > end-start {
start = i - (len-1)/2
end = i + len/2
}
}
return s[start : end+1]
}
func expandAroundCenter(s string, left, right int) int {
L := left
R := right
for L >= 0 && R < len(s) && s[L] == s[R] {
L--
R++
}
return R - L - 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment