Created
March 6, 2020 16:10
-
-
Save Skarlso/78a6c1ecd62357c2ef32178962b963be to your computer and use it in GitHub Desktop.
Longest palindrome in string using Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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