-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1032. Stream of Characters.rb
55 lines (45 loc) · 1.14 KB
/
1032. Stream of Characters.rb
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
class Node
attr_reader :children
attr_accessor :eow
def initialize()
@children = {}
end
def add(word)
curr = self
word.each_char do |char|
curr.children[char] ||= Node.new
curr = curr.children[char]
end
curr.eow = true
end
end
class StreamChecker
def initialize(words)
# hash map {"char" => Node}
@root = Node.new
words.each {|w| @root.add(w.reverse) }
@letters = []
end
=begin
:type letter: Character
:rtype: Boolean
=end
def query(letter)
@letters << letter
curr_node = @root
(@letters.length - 1).downto(0) do |i|
char = @letters[i]
if curr_node.children[char].nil?
return false
elsif curr_node.children[char].eow
return true
else
curr_node = curr_node.children[@letters[i]]
end
end
false
end
end
# Your StreamChecker object will be instantiated and called as such:
# obj = StreamChecker.new(words)
# param_1 = obj.query(letter)