Skip to content

Commit

Permalink
208
Browse files Browse the repository at this point in the history
  • Loading branch information
TedTran2019 committed Jul 15, 2022
1 parent 53c3815 commit c1f1d5e
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions ruby/208-Implement-Trie.rb
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

0 comments on commit c1f1d5e

Please sign in to comment.