LC 0745 [H] Prefix and Suffix Search - ALawliet/algorithms GitHub Wiki

{
  '.': 0,
  '.t': 0,
  '.at': 0,
  '.bat': 0,
  'b.': 0,
  'b.t': 0,
  'b.at': 0,
  'b.bat': 0,
  'ba.': 0,
  'ba.t': 0,
  'ba.at': 0,
  'ba.bat': 0,
  'bat.': 0,
  'bat.t': 0,
  'bat.at': 0,
  'bat.bat': 0,
}
class WordFilter(object):

    def __init__(self, words):
        """
        :type words: List[str]
        """
        self.dic = {}
        for weight, word in enumerate(words):
            n = len(word)
            for p in range(1, n + 1): # prefix like this because of exclusive index
                for s in range(n):
                    self.dic[word[:p]+'#'+word[s:]] = weight
        

    def f(self, prefix, suffix):
        """
        :type prefix: str
        :type suffix: str
        :rtype: int
        """
        return self.dic.get(prefix+'#'+suffix, -1)