Stream of Characters (H)
題目
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 lastkcharacters 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 <= 20001 <= 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.
題意
給定一個單詞字典,并按順序一連串字母,判斷字典中是否存在以當前輸入字母為結尾的單詞,
思路
找單詞一般可以用字典樹,同時注意到這里需要從單詞末尾找到單詞開頭,所以構建字典樹時也要倒著來,
代碼實作
Java
class StreamChecker {
private Node root;
private List<Character> queries;
public StreamChecker(String[] words) {
root = new Node();
queries = new ArrayList<>();
for (String word : words) {
buildTrie(word);
}
}
public boolean query(char letter) {
queries.add(letter);
Node p = root;
for (int i = queries.size() - 1; i >= 0; i--) {
char c = queries.get(i);
if (p.children[c - 'a'] != null) {
p = p.children[c - 'a'];
if (p.end) {
return true;
}
} else {
return false;
}
}
return false;
}
private void buildTrie(String word) {
Node p = root;
for (int i = word.length() - 1; i >= 0; i--) {
char c = word.charAt(i);
if (p.children[c - 'a'] == null) {
p.children[c - 'a'] = new Node();
}
p = p.children[c - 'a'];
}
p.end = true;
}
}
class Node {
Node[] children;
boolean end;
Node() {
children = new Node[26];
end = false;
}
}
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker obj = new StreamChecker(words); boolean param_1 =
* obj.query(letter);
*/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/145111.html
標籤:其他
上一篇:回文樹在線剖分???
