class Node: def __init__(self): self.children = {} # Char : Node self.end = False # finished or not class Trie: def __init__(self): self.root = Node()
def insert(self, word): current = self.root for letter in word: if letter not in current.children: # not child current.children[letter] = Node() # new node current = current.children[letter] # to child node current.end = True # leaf
def search(self, word): current = self.root for letter in word: if letter not in current.children: return False # not found else: current = current.children[letter] # to child node return current.end # found
def startsWith(self, prefix): current = self.root for letter in prefix: if letter not in current.children: return False # not found else: current = current.children[letter] # to child node return True # found
Design a special dictionary that searches the words in it by a prefix and a suffix.
Implement the WordFilter class:
WordFilter(string[] words) Initializes the object with the words in the dictionary.
f(string pref, string suff) Returns the index of the word in the dictionary, which has the prefix pref and the suffix suff. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1.
Example 1:
1 2 3 4 5 6 7 8
Input ["WordFilter", "f"] [[["apple"]], ["a", "e"]] Output [null, 0] Explanation WordFilter wordFilter = new WordFilter(["apple"]); wordFilter.f("a", "e"); // return 0, because the word at index 0 has prefix = "a" and suffix = "e".
TC, SC: O(n*kˆ2) import java.util.*; class WordFilter { class Trie { class TrieNode { private TrieNode[] children; private List<Integer> indices; // index of current word public TrieNode() { children = new TrieNode[26]; indices = new ArrayList<>(); } } private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word, int i) { TrieNode cur = root; for (char c : word.toCharArray()) { int idx = c-'a'; // minus begin word, get char index cur.indices.add(i); // if no character if (cur.children[idx] == null) { cur.children[idx] = new TrieNode(); } cur = cur.children[idx]; // to next child } cur.indices.add(i); // add index } public List<Integer> find(String prefix) { TrieNode cur = root; for (char c : prefix.toCharArray()) { int idx = c-'a'; if (cur.children[idx] == null) return new ArrayList<>(); cur = cur.children[idx]; } return cur.indices; } } private Trie t; private String[] words; public WordFilter(String[] words) { t = new Trie(); this.words = words; for (int i = 0; i < words.length; i++) { t.insert(words[i], i); } } // find word start with prexix and end with suffix, return index public int f(String prefix, String suffix) { List<Integer> l = t.find(prefix); for (int i = l.size()-1; i >= 0; i--) { if (words[l.get(i)].endsWith(suffix)) return l.get(i); } return -1; } public static void main(String[] args) { String[] str = {"apple"}; WordFilter wordFilter = new WordFilter(str); System.out.println(wordFilter.f("a", "e")); } }