forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
53c3815
commit c1f1d5e
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
class Trie | ||
END_OF_WORD = 'END' | ||
|
||
def initialize | ||
@root = {} | ||
end | ||
|
||
def insert(word) | ||
curr = @root | ||
last_idx = word.length - 1 | ||
word.each_char.with_index do |char, idx| | ||
curr[char] ||= {} | ||
curr = curr[char] | ||
curr[END_OF_WORD] = true if last_idx == idx | ||
end | ||
nil | ||
end | ||
|
||
def search(word) | ||
curr = @root | ||
word.each_char do |char| | ||
return false unless curr[char] | ||
|
||
curr = curr[char] | ||
end | ||
!!curr[END_OF_WORD] | ||
end | ||
|
||
def starts_with(prefix) | ||
curr = @root | ||
prefix.each_char do |char| | ||
return false unless curr[char] | ||
|
||
curr = curr[char] | ||
end | ||
true | ||
end | ||
end |