Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit ad15aa4

Browse files
committed
1032 done
1 parent ad7265e commit ad15aa4

File tree

2 files changed

+29
-22
lines changed

2 files changed

+29
-22
lines changed

Algorithms/1032.stream-of-characters/stream-of-characters.go

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,62 +2,58 @@ package problem1032
22

33
// StreamChecker check letters
44
type StreamChecker struct {
5-
tree *trie
6-
stream []int8
75
max int
6+
trie *trie
7+
stream []int8
88
}
99

1010
// Constructor returns StreamChecker
1111
func Constructor(words []string) StreamChecker {
12-
maxLen := 0
13-
tree := &trie{}
14-
for _, word := range words {
15-
maxLen = max(maxLen, len(word))
16-
tree.insert(word)
12+
m := 0
13+
t := &trie{}
14+
for _, w := range words {
15+
m = max(m, len(w))
16+
t.insert(w)
1717
}
1818
return StreamChecker{
19-
tree: tree,
20-
stream: make([]int8, 0, 40001),
21-
max: maxLen,
19+
max: m,
20+
trie: t,
21+
stream: make([]int8, 0, 1024),
2222
}
2323
}
2424

2525
// Query returns true if letter in words
2626
func (sc *StreamChecker) Query(letter byte) bool {
2727
sc.stream = append(sc.stream, int8(letter-'a'))
28-
n := len(sc.stream)
29-
cur := sc.tree
28+
n, t := len(sc.stream), sc.trie
3029
for i := 1; i <= sc.max && i <= n; i++ {
3130
index := sc.stream[n-i]
32-
if cur.next[index] == nil {
31+
if t.next[index] == nil {
3332
return false
3433
}
35-
cur = cur.next[index]
36-
if cur.isWord {
34+
t = t.next[index]
35+
if t.isWord {
3736
return true
3837
}
3938
}
4039
return false
4140
}
4241

43-
// TODO: var isWord = &trie{}
44-
4542
type trie struct {
4643
next [26]*trie
4744
isWord bool
4845
}
4946

5047
func (t *trie) insert(word string) {
5148
n := len(word)
52-
cur := t
5349
for i := n - 1; i >= 0; i-- {
5450
index := int(word[i] - 'a')
55-
if cur.next[index] == nil {
56-
cur.next[index] = &trie{}
51+
if t.next[index] == nil {
52+
t.next[index] = &trie{}
5753
}
58-
cur = cur.next[index]
54+
t = t.next[index]
5955
if i == 0 {
60-
cur.isWord = true
56+
t.isWord = true
6157
}
6258
}
6359
}

Algorithms/1032.stream-of-characters/stream-of-characters_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,3 +94,14 @@ func Test_Case_6(t *testing.T) {
9494
ast.Equal(expects[i], streamChecker.Query(q), "%d:%s", i, string(querys[:i+1]))
9595
}
9696
}
97+
98+
func Test_Case_7(t *testing.T) {
99+
ast := assert.New(t)
100+
//
101+
words := []string{"cd"}
102+
streamChecker := Constructor(words)
103+
//
104+
ast.False(streamChecker.Query('c')) // return false
105+
ast.False(streamChecker.Query('a')) // return false
106+
ast.False(streamChecker.Query('d')) // return false
107+
}

0 commit comments

Comments
 (0)