-
Notifications
You must be signed in to change notification settings - Fork 17
/
is-subsequence.go
63 lines (52 loc) · 1.04 KB
/
is-subsequence.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
package main
import (
"errors"
)
// TODO: add DP solution
func isSubsequence(s string, t string) bool {
bisect := func(arr []int, val int) (int, error) {
left, right := -1, len(arr)
for middle := (left + right) / 2; left+1 < right; middle = (left + right) / 2 {
if arr[middle] > val {
right = middle
} else {
left = middle
}
}
if right < len(arr) {
return arr[right], nil
}
return -1, errors.New("")
}
charMap := map[rune][]int{}
for pos, char := range t {
if _, ok := charMap[char]; !ok {
charMap[char] = []int{}
}
charMap[char] = append(charMap[char], pos)
}
prevPos := -1
for _, char := range s {
if nextPos, err := bisect(charMap[char], prevPos); err == nil {
prevPos = nextPos
} else {
return false
}
}
return true
}
func isSubsequenceGreedyTwoPointers(s string, t string) bool {
if len(s) == 0 {
return true
}
patternPtr := 0
for strPtr := range t {
if t[strPtr] == s[patternPtr] {
patternPtr += 1
if patternPtr == len(s) {
return true
}
}
}
return false
}