Last active
March 4, 2020 14:34
-
-
Save kzkn/4a489accba3992095c8a1a8f65f3ed0e to your computer and use it in GitHub Desktop.
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
class WordFilter | |
def initialize(words) | |
@root = Node.new | |
words.each.with_index do |w, weight| | |
(0..w.size).each do |len| | |
s = "#{w[-len, len]}@#{w}" | |
@root.add_word(weight, s, 0) | |
end | |
end | |
end | |
def f(prefix, suffix) | |
query = "#{suffix}@#{prefix}" | |
node = @root.find(query, 0) | |
node&.weight || -1 | |
end | |
class Node | |
attr_reader :weight | |
def initialize | |
@weight = -1 | |
end | |
def add_word(weight, word, idx) | |
@weight = [@weight, weight].max | |
return if word.size == idx | |
ch = word[idx] | |
child = children[ch] | |
unless child | |
child = Node.new | |
children[ch] = child | |
end | |
child.add_word(weight, word, idx + 1) | |
end | |
def find(prefix, idx) | |
return self if prefix.size == idx | |
ch = prefix[idx] | |
child = children[ch] | |
child&.find(prefix, idx + 1) | |
end | |
def children | |
@children ||= {} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment