Skip to content

Commit 7e9c937

Browse files
committed
Add 680. Valid Palindrome II
1 parent dad884a commit 7e9c937

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package valid_palindrome_II
2+
3+
func validPalindrome(s string) bool {
4+
l := 0
5+
r := len(s) - 1
6+
7+
for l <= r {
8+
if s[l] != s[r] {
9+
return CheckPalindrome(s, l, r - 1) || CheckPalindrome(s,l + 1, r)
10+
}
11+
l ++
12+
r --
13+
}
14+
15+
return true
16+
}
17+
18+
// Helper
19+
func CheckPalindrome(s string, i, j int) bool {
20+
for i < j {
21+
if s[i] != s[j] {
22+
return false
23+
}
24+
i ++
25+
j --
26+
}
27+
return true
28+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package valid_palindrome_II
2+
3+
import "testing"
4+
5+
func TestValidPalindrome(t *testing.T) {
6+
tests := []struct {
7+
name string
8+
s string
9+
expectedResult bool
10+
} {
11+
{
12+
name: "Test Case 1",
13+
s: "aba",
14+
expectedResult: true,
15+
},
16+
{
17+
name: "Test Case 2",
18+
s: "abca",
19+
expectedResult: true,
20+
},
21+
{
22+
name: "Test Case 3",
23+
s: "abc",
24+
expectedResult: false,
25+
},
26+
}
27+
28+
for _, test := range tests {
29+
t.Run(test.name, func(t *testing.T) {
30+
got := validPalindrome(test.s)
31+
32+
if got != test.expectedResult {
33+
t.Errorf("checkPalindrome(%s) = %t; want = %t", test.s, got, test.expectedResult)
34+
}
35+
})
36+
}
37+
}

0 commit comments

Comments
 (0)