码迷,mamicode.com
首页 > 其他好文 > 详细

Prefix and Suffix Search

时间:2019-07-27 14:28:31      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:ret   i++   begin   public   lte   support   bsp   search   gen   

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 public class WordFilter {
 2     private TrieNode root = new TrieNode( , -1);
 3     public WordFilter(String[] words) {
 4         for (int weight = 0; weight < words.length; weight++) {
 5             List<String> suffixList = generateSuffixList(words[weight]);
 6             for (String word : suffixList) {
 7                 addWord(word, weight);
 8             }
 9         }
10     }
11 
12     public void addWord(String word, int weight) {
13         TrieNode current = root;
14         for (int i = 0; i < word.length(); i++) {
15             char ch = word.charAt(i);
16             TrieNode node = current.getChildNode(ch);
17             if (node == null) {
18                 current.map.put(ch, new TrieNode(ch, weight));
19                 node = current.getChildNode(ch);
20             }
21             node.weight = Math.max(weight, node.weight);
22             current = node;
23         }
24     }
25 
26     private List<String> generateSuffixList(String word) {
27         List<String> suffixList = new ArrayList<>();
28         int length = word.length();
29         for (int i = length; i >= 0; i--) {
30             String sub = word.substring(i, length);
31             suffixList.add(sub + "_" + word);
32         }
33         return suffixList;
34     }
35 
36     public int f(String prefix, String suffix) {
37         if (root == null) return -1;
38         TrieNode current = root;
39         String word = suffix + "_" + prefix;
40         for (char ch : word.toCharArray()) {
41             current = current.getChildNode(ch);
42             if (current == null) {
43                 return -1;
44             }
45         }
46         return current.weight;
47     }
48 }

 

Prefix and Suffix Search

标签:ret   i++   begin   public   lte   support   bsp   search   gen   

原文地址:https://www.cnblogs.com/beiyeqingteng/p/11254893.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!