Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0000782

Browse files
author
openset
committed
Add: Longest Palindromic Substring
1 parent f37ac3b commit 0000782

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,20 @@
11
package longest_palindromic_substring
2+
3+
func longestPalindrome(s string) string {
4+
start, maxLen, l := 0, 0, len(s)
5+
for i := 0; i < l; i++ {
6+
expandAroundCenter(s, i, i, &start, &maxLen)
7+
expandAroundCenter(s, i, i+1, &start, &maxLen)
8+
}
9+
return s[start : start+maxLen]
10+
}
11+
12+
func expandAroundCenter(s string, l, r int, start, maxLen *int) {
13+
for l >= 0 && r < len(s) && s[l] == s[r] {
14+
l, r = l-1, r+1
15+
}
16+
if r-l-1 > *maxLen {
17+
*maxLen = r - l - 1
18+
*start = l + 1
19+
}
20+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,39 @@
11
package longest_palindromic_substring
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input string
7+
expected string
8+
}
9+
10+
func TestLongestPalindrome(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: "babad",
14+
expected: "bab",
15+
},
16+
{
17+
input: "cbbd",
18+
expected: "bb",
19+
},
20+
{
21+
input: "",
22+
expected: "",
23+
},
24+
{
25+
input: "a",
26+
expected: "a",
27+
},
28+
{
29+
input: "abbba",
30+
expected: "abbba",
31+
},
32+
}
33+
for _, tc := range tests {
34+
output := longestPalindrome(tc.input)
35+
if output != tc.expected {
36+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
37+
}
38+
}
39+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /