This repository has been archived by the owner on Jun 24, 2021. It is now read-only.
forked from hoanhan101/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalid_palindrome_test.go
81 lines (66 loc) · 1.64 KB
/
valid_palindrome_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
Problem:
- Given a string, determine if it is a palindrome, considering only
alphanumeric characters and ignoring cases.
Example:
- Input: "A man, a plan, a canal: Panama"
Output: true
- Input: "race a car"
Output: false
Approach:
- Use two pointers approach that have one point to the start of the string and
the other point at the end.
- Move them toward each other and compare if they're the same characters while
skipping non-alphanumeric characters and ignoring cases.
Solution:
- Have a pointer point to the start of the string and the other point at the end.
- Make the string lower case.
- While the start one is less the end one, ignore non-alphanumeric characters
and move them toward each other.
Cost:
- O(n) time, O(1) space.
*/
package leetcode
import (
"strings"
"testing"
"unicode"
"github.com/hoanhan101/algo/common"
)
func TestIsPalindrome(t *testing.T) {
tests := []struct {
in string
expected bool
}{
{"A man, a plan, a canal: Panama", true},
{"race a car", false},
}
for _, tt := range tests {
result := isPalindrome(tt.in)
common.Equal(t, tt.expected, result)
}
}
func isPalindrome(s string) bool {
start := 0
end := len(s) - 1
// make the input string lower case.
s = strings.ToLower(s)
for start < end {
// if the letter at the start and end pointers are non-alphanumeric
// then skip them.
for !unicode.IsLetter([]rune(s)[start]) {
start++
}
for !unicode.IsLetter([]rune(s)[end]) {
end--
}
// return false immediately if two corresponding characters are not
// matching.
if []rune(s)[start] != []rune(s)[end] {
return false
}
start++
end--
}
return true
}