Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c1f1d5e

Browse files
committed
208
1 parent 53c3815 commit c1f1d5e

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

ruby/208-Implement-Trie.rb

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Trie
2+
END_OF_WORD = 'END'
3+
4+
def initialize
5+
@root = {}
6+
end
7+
8+
def insert(word)
9+
curr = @root
10+
last_idx = word.length - 1
11+
word.each_char.with_index do |char, idx|
12+
curr[char] ||= {}
13+
curr = curr[char]
14+
curr[END_OF_WORD] = true if last_idx == idx
15+
end
16+
nil
17+
end
18+
19+
def search(word)
20+
curr = @root
21+
word.each_char do |char|
22+
return false unless curr[char]
23+
24+
curr = curr[char]
25+
end
26+
!!curr[END_OF_WORD]
27+
end
28+
29+
def starts_with(prefix)
30+
curr = @root
31+
prefix.each_char do |char|
32+
return false unless curr[char]
33+
34+
curr = curr[char]
35+
end
36+
true
37+
end
38+
end

0 commit comments

Comments
 (0)