Design a special dictionary with some words that searchs the words in it by a prefix and a suffix.
Implement the WordFilter
class:
WordFilter(string[] words)
Initializes the object with thewords
in the dictionary.f(string prefix, string suffix)
Returns the index of the word in the dictionary, which has the prefixprefix
and the suffixsuffix
. 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:
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".
Constraints:
1 <= words.length <= 15000
1 <= words[i].length <= 10
1 <= prefix.length, suffix.length <= 10
words[i]
,prefix
andsuffix
consist of lower-case English letters only.- At most
15000
calls will be made to the functionf
.
思路:这题出的很巧妙,用 { 来分割suffix 和prefix, 为什么是 { 是 The reason we use '{' is because '{' is the char right after 'z' in ASCII. Therefore, we could directly build array of size 27.
// apple -> {apple, e{apple, le{apple, ple{apple, pple{apple, apple{apple;
// 这里也就是所有可能的变形,全部都是针对一个word,所以weight都是i;
另外还有个点需要注意的是:// 因为所有的都是代表同一个word,而且prefix,suffix都有可能在path上搜,所以每个点都要赋值为weight;
class WordFilter {
private class TrieNode {
public TrieNode[] children;
public int weight;
public TrieNode () {
this.children = new TrieNode[27];
this.weight = 0;
}
}
private class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word, int weight) {
TrieNode cur = root;
for(int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if(cur.children[c - 'a'] == null) {
cur.children[c - 'a'] = new TrieNode();
}
cur = cur.children[c - 'a'];
// 因为所有的都是代表同一个word,而且prefix,suffix都有可能在path上搜,所以每个点都要赋值为weight;
cur.weight = weight;
}
}
public int startWith(String word) {
TrieNode cur = root;
for(int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if(cur.children[c - 'a'] == null) {
return -1;
}
cur = cur.children[c - 'a'];
}
return cur.weight;
}
}
private Trie trie;
public WordFilter(String[] words) {
trie = new Trie();
for(int i = 0; i < words.length; i++) {
String word = words[i];
for(int j = 0; j <= word.length(); j++) {
// apple -> {apple, e{apple, le{apple, ple{apple, pple{apple, apple{apple;
// 这里也就是所有可能的变形,全部都是针对一个word,所以weight都是i;
trie.insert(word.substring(j, word.length()) + '{' + word, i);
}
}
}
public int f(String prefix, String suffix) {
// 注意这里是suffix + '{' + prefix, 因为加进去的时候,是suffix在前面;
return trie.startWith(suffix + '{' + prefix);
}
}
/**
* Your WordFilter object will be instantiated and called as such:
* WordFilter obj = new WordFilter(words);
* int param_1 = obj.f(prefix,suffix);
*/