-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrieSearch.rb
68 lines (51 loc) · 961 Bytes
/
trieSearch.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
class TrieNode
def initialize
@children = [nil] * 125
@lastOfWord = false
end
def children
@children
end
def setChildren(index, node)
@children[index] = node
end
def lastOfWord
@lastOfWord
end
def setLastOfWord
@lastOfWord = true
end
end
class Trie
def initialize
@root = TrieNode.new
end
def getNode()
TrieNode.new
end
def getCharIndex(k)
k.to_s.ord - 'a'.ord
end
def insert(key)
pCrawl = @root
key.each_char do |k|
k_index = getCharIndex(k)
if !pCrawl.children.index(k_index)
pCrawl.children[k_index] = getNode()
end
pCrawl = pCrawl.children[k_index]
end
pCrawl.setLastOfWord
end
def search(key)
pCrawl = @root
key.each_char do |k|
k_index = getCharIndex(k)
if !pCrawl.children[k_index]
return false
end
pCrawl = pCrawl.children[k_index]
end
pCrawl.lastOfWord
end
end