Prefix and Suffix Search

时间:2021-03-24 17:17:13

Given many wordswords[i] has weight i.

Design a class WordFilter that supports one function, WordFilter.f(String prefix, String suffix). It will return the word with given prefix and suffix with maximum weight. If no word exists, return -1.

Examples:

Input:
WordFilter(["apple"])
WordFilter.f("a", "e") // returns 0
WordFilter.f("b", "") // returns -1 分析:因为要找出word一定begin with prefix,以及end with suffix,有点麻烦。其实找begin with prefix不麻烦,麻烦的是怎么找end with suffix. 这里有点巧的方法是对于每个word,把它所有的
suffx_word放在trie里,比如apple, 我们就把 "_apple", "e_apple", "le_apple", "ple_apple", "pple_apple", "apple_apple" 都存在trie里。这样可以用trie把所有的情况都包括了。
 class TrieNode {
char ch;
int weight;
Map<Character, TrieNode> map; public TrieNode(char ch, int weight) {
this.ch = ch;
this.weight = weight;
map = new HashMap<>();
} public TrieNode getChildNode(char ch) {
return map.get(ch);
}
} public class WordFilter {
private TrieNode root = new TrieNode(' ', -);
public WordFilter(String[] words) {
for (int weight = ; weight < words.length; weight++) {
List<String> suffixList = generateSuffixList(words[weight]);
for (String word : suffixList) {
addWord(word, weight);
}
}
} public void addWord(String word, int weight) {
TrieNode current = root;
for (int i = ; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = current.getChildNode(ch);
if (node == null) {
current.map.put(ch, new TrieNode(ch, weight));
node = current.getChildNode(ch);
}
node.weight = Math.max(weight, node.weight);
current = node;
}
}
private List<String> generateSuffixList(String word) {
List<String> suffixList = new ArrayList<>();
int length = word.length();
for (int i = length; i >= ; i--) {
String sub = word.substring(i, length);
suffixList.add(sub + "_" + word);
}
return suffixList;
} public int f(String prefix, String suffix) {
if (root == null) return -;
TrieNode current = root; String word = suffix + "_" + prefix;
for (char ch : word.toCharArray()) {
current = current.getChildNode(ch);
if (current == null) {
return -;
}
}
return current.weight;
}
}