diff --git a/problems/longest-palindromic-substring/longest_palindromic_substring.go b/problems/longest-palindromic-substring/longest_palindromic_substring.go index ed3563a6b..cfb0f679e 100644 --- a/problems/longest-palindromic-substring/longest_palindromic_substring.go +++ b/problems/longest-palindromic-substring/longest_palindromic_substring.go @@ -1 +1,20 @@ package longest_palindromic_substring + +func longestPalindrome(s string) string { + start, maxLen, l := 0, 0, len(s) + for i := 0; i < l; i++ { + expandAroundCenter(s, i, i, &start, &maxLen) + expandAroundCenter(s, i, i+1, &start, &maxLen) + } + return s[start : start+maxLen] +} + +func expandAroundCenter(s string, l, r int, start, maxLen *int) { + for l >= 0 && r < len(s) && s[l] == s[r] { + l, r = l-1, r+1 + } + if r-l-1 > *maxLen { + *maxLen = r - l - 1 + *start = l + 1 + } +} diff --git a/problems/longest-palindromic-substring/longest_palindromic_substring_test.go b/problems/longest-palindromic-substring/longest_palindromic_substring_test.go index ed3563a6b..465dead42 100644 --- a/problems/longest-palindromic-substring/longest_palindromic_substring_test.go +++ b/problems/longest-palindromic-substring/longest_palindromic_substring_test.go @@ -1 +1,39 @@ package longest_palindromic_substring + +import "testing" + +type caseType struct { + input string + expected string +} + +func TestLongestPalindrome(t *testing.T) { + tests := [...]caseType{ + { + input: "babad", + expected: "bab", + }, + { + input: "cbbd", + expected: "bb", + }, + { + input: "", + expected: "", + }, + { + input: "a", + expected: "a", + }, + { + input: "abbba", + expected: "abbba", + }, + } + for _, tc := range tests { + output := longestPalindrome(tc.input) + if output != tc.expected { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}