745. Prefix and Suffix Search
use Trie
class WordFilter {
class TrieNode {
Map<Character, TrieNode> sons;
int weight;
TrieNode() {
this.sons = new HashMap<>();
this.weight = weight;
}
}
private TrieNode root;
private void insert(String word, int weight) {
TrieNode node = root;
for (char c : word.toCharArray()) {
node.sons.putIfAbsent(c, new TrieNode());
node = node.sons.get(c);
node.weight = weight;
}
}
public WordFilter(String[] words) {
root = new TrieNode();
for (int i = 0; i < words.length; i++) {
int weight = i;
String word = "{" + words[i];
insert(word, weight);
for (int j = 0; j < word.length(); j++) {
insert(word.substring(j+1) + word, weight);
}
}
}
public int f(String prefix, String suffix) {
TrieNode node = root;
for (char c : (suffix + "{" + prefix).toCharArray()) {
if (node.sons.get(c) == null) {
return -1;
}
node = node.sons.get(c);
}
return node.weight;
}
}
/**
* Your WordFilter object will be instantiated and called as such:
* WordFilter obj = new WordFilter(words);
* int param_1 = obj.f(prefix,suffix);
*/use HashMap
Last updated