Prefix and Suffix Search

Posted beiyeqingteng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 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的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Prefix and Suffix Search 前后缀搜索

mybatis之<trim prefix="" suffix="" suffixOverrides="" prefixOverride

[AGC040E]Prefix Suffix Addition

D. Prefix-Suffix Palindrome (马拉车)

Prefix-Suffix Palindrome (Hard version) (Manacher)

1326D Prefix-Suffix Palindrome (Hard version) (manacher)