Implement the StreamChecker
class as follows:
StreamChecker(words)
: Constructor, init the data structure with the given words.query(letter)
: returns true if and only if for somek >= 1
, the lastk
characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list.
Example:
StreamChecker streamChecker = new StreamChecker(["cd","f","kl"]); // init the dictionary. streamChecker.query('a'); // return false streamChecker.query('b'); // return false streamChecker.query('c'); // return false streamChecker.query('d'); // return true, because 'cd' is in the wordlist streamChecker.query('e'); // return false streamChecker.query('f'); // return true, because 'f' is in the wordlist streamChecker.query('g'); // return false streamChecker.query('h'); // return false streamChecker.query('i'); // return false streamChecker.query('j'); // return false streamChecker.query('k'); // return false streamChecker.query('l'); // return true, because 'kl' is in the wordlist Note:
1 <= words.length <= 2000
1 <= words[i].length <= 2000
- Words will only consist of lowercase English letters.
- Queries will only consist of lowercase English letters.
- The number of queries is at most 40000.
思路: 这题就是考察trie,但是tricky的地方就是要反向存string,然后letter进来之后append,append之后也是反向查找;如果碰见是cur != null && cur.isword 就返回true;
class StreamChecker {
public class TrieNode {
public TrieNode[] children;
public boolean isword;
public String word;
public TrieNode() {
this.children = new TrieNode[26];
this.isword = false;
this.word = null;
}
}
public class Trie {
public TrieNode root;
public Trie() {
this.root = new TrieNode();
}
public void insertWord(String word) {
TrieNode cur = root;
for(int i = word.length() - 1; i >= 0; i--) {
char c = word.charAt(i);
if(cur.children[c - 'a'] == null) {
cur.children[c - 'a'] = new TrieNode();
}
cur = cur.children[c - 'a'];
}
cur.isword = true;
cur.word = word;
}
}
private StringBuilder sb;
private Trie trie;
public StreamChecker(String[] words) {
sb = new StringBuilder();
this.trie = new Trie();
for(String word: words) {
trie.insertWord(word);
}
}
public boolean query(char letter) {
sb.append(letter);
TrieNode cur = trie.root;
for(int i = sb.length() - 1; i >= 0; i--) {
char c = sb.charAt(i);
if(cur.children[c - 'a'] == null) {
return false;
}
cur = cur.children[c - 'a'];
if(cur.isword) {
return true;
}
}
return false;
}
}
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker obj = new StreamChecker(words);
* boolean param_1 = obj.query(letter);
*/