Skip to content

Commit 0f22496

Browse files
committed
add 0005
1 parent 0a8985f commit 0f22496

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

algorithms/0005/main.go

+37-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,41 @@
11
package _0005
22

33
func longestPalindrome(s string) string {
4-
return s
4+
if len(s) == 1 {
5+
return s
6+
}
7+
str := s[0:1]
8+
if len(s) == 2 {
9+
if s[0] == s[1] {
10+
return s
11+
}
12+
return str
13+
}
14+
for i := 0; i < len(s); i++ {
15+
j := 2
16+
for j <= len(s) && i <= len(s)-j {
17+
sub := s[i : i+j]
18+
if check(sub) {
19+
if len(sub) > len(str) {
20+
str = sub
21+
}
22+
}
23+
j++
24+
}
25+
}
26+
27+
return str
28+
}
29+
30+
func check(s string) bool {
31+
mid := len(s) / 2
32+
if len(s)%2 == 0 {
33+
mid = mid - 1
34+
}
35+
for i := 0; i <= mid; i++ {
36+
if !(s[i] == s[len(s)-i-1]) {
37+
return false
38+
}
39+
}
40+
return true
541
}

0 commit comments

Comments
 (0)