-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path208_implement_trie_prefix_tree.rb
70 lines (54 loc) · 1 KB
/
208_implement_trie_prefix_tree.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# frozen_string_literal: true
# https://leetcode.com/problems/implement-trie-prefix-tree/
class Trie
# Init
def initialize
@root = ::Node208.new
end
# @param {String} word
# @return {Void}
def insert(word)
curr = @root
word.each_char do |c|
node = curr.children[c]
unless node
node = ::Node208.new
curr.children[c] = node
end
curr = node
end
curr.nd = true
end
# @param {String} word
# @return {Boolean}
def search(word)
curr = @root
word.each_char do |c|
node = curr.children[c]
return false unless node
curr = node
end
curr.nd
end
# @param {String} word
# @return {Boolean}
def starts_with(prefix)
curr = @root
prefix.each_char do |c|
node = curr.children[c]
return false unless node
curr = node
end
true
end
end
private
# Node for Trie
class Node208
attr_accessor :children, :nd
# Init
def initialize
@children = {}
@nd = false
end
end