-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautoCompletion.rb
88 lines (71 loc) · 1.31 KB
/
autoCompletion.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class TrieNode
attr_accessor :children, :last
def initialize
@children = {}
@last = false
end
end
class Trie
def initialize
@root = TrieNode.new
@word_list = []
end
def insert_all(keys)
keys.each do |key|
insert(key)
end
end
def insert(key)
node = @root
key.each_char do |k|
if !node.children[k]
node.children[k] = TrieNode.new
end
node = node.children[k]
end
node.last = true
end
def search(key)
node = @root
found = true
key.each_char do |k|
if !node.children[k]
found = false
break
end
node = node.children[k]
end
return node.last && found
end
def suggestions(node, word)
if node.last
@word_list << word
end
node.children.each do |(key, child)|
suggestions(child, word + key)
end
end
def suggestions_lists(key)
node = @root
temp_word = ""
found = true
key.each_char do |k|
if !node.children[k]
found = false
break;
end
temp_word += k
node = node.children[k]
end
if !found
return []
end
suggestions(node, temp_word)
return @word_list
end
end
def auto_completion(words, target)
t = Trie.new
t.insert_all(words)
t.suggestions_lists(target)
end