Prefix and Suffix Search

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把所有的情况都包括了。
 1 class TrieNode {
 2     char ch;
 3     int weight;
 4     Map<Character, TrieNode> map;
 5 
 6     public TrieNode(char ch, int weight) {
 7         this.ch = ch;
 8         this.weight = weight;
 9         map = new HashMap<>();
10     }
11 
12     public TrieNode getChildNode(char ch) {
13         return map.get(ch);
14     }
15 }
16 
17 public class WordFilter {
18     private TrieNode root = new TrieNode(' ', -1);
19     public WordFilter(String[] words) {
20         for (int weight = 0; weight < words.length; weight++) {
21             List<String> suffixList = generateSuffixList(words[weight]);
22             for (String word : suffixList) {
23                 addWord(word, weight);
24             }
25         }
26     }
27     
28     public void addWord(String word, int weight) {
29         TrieNode current = root;
30         for (int i = 0; i < word.length(); i++) {
31             char ch = word.charAt(i);
32             TrieNode node = current.getChildNode(ch);
33             if (node == null) {
34                 current.map.put(ch, new TrieNode(ch, weight));
35                 node = current.getChildNode(ch);
36             }
37             node.weight = Math.max(weight, node.weight);
38             current = node;
39         }
40     }
41     private List<String> generateSuffixList(String word) {
42         List<String> suffixList = new ArrayList<>();
43         int length = word.length();
44         for (int i = length; i >= 0; i--) {
45             String sub = word.substring(i, length);
46             suffixList.add(sub + "_" + word);
47         }
48         return suffixList;
49     }
50     
51     
52     public int f(String prefix, String suffix) {
53         if (root == null) return -1;
54         TrieNode current = root;
55         
56         String word = suffix + "_" + prefix;
57         for (char ch : word.toCharArray()) {
58             current = current.getChildNode(ch);
59             if (current == null) {
60                 return -1;
61             }
62         }
63         return current.weight;
64     }
65 }

 

posted @ 2019-07-27 14:18  北叶青藤  阅读(274)  评论(0编辑  收藏  举报