LeetCode 745. Prefix and Suffix Search

原题链接在这里:https://leetcode.com/problems/prefix-and-suffix-search/

题目:

Design a special dictionary which has some words and allows you to search the words in it by a prefix and a suffix.

Implement the WordFilter class:

  • WordFilter(string[] words) Initializes the object with the words in the dictionary.
  • f(string prefix, string suffix) Returns the index of the word in the dictionary which has the prefix prefix and the suffix suffix. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1.

Example 1:

Input
["WordFilter", "f"]
[[["apple"]], ["a", "e"]]
Output
[null, 0]

Explanation
WordFilter wordFilter = new WordFilter(["apple"]);
wordFilter.f("a", "e"); // return 0, because the word at index 0 has prefix = "a" and suffix = 'e".

Constraints:

  • 1 <= words.length <= 15000
  • 1 <= words[i].length <= 10
  • 1 <= prefix.length, suffix.length <= 10
  • words[i]prefix and suffix consist of lower-case English letters only.
  • At most 15000 calls will be made to the function f.

题解:

For each word in words, iterate the word, make every possible suffix + "{" + word as a new String. Insert this new String in Trie.

When find f(prefix, suffix), find startsWith suffix + "{" + prefix in Trie.

Time Complexity: O(m * l^2). m = words.length. l is average length of word in words. insert takes O(l) time.

Space: O(m * l^2).

AC Java:

 1 class WordFilter {
 2     TrieNode root;
 3     
 4     public WordFilter(String[] words) {
 5         root = new TrieNode();
 6         for(int i = 0; i<words.length; i++){
 7             String w = words[i];
 8             for(int j = 0; j<=w.length(); j++){
 9                 insert(w.substring(j) + "{" + w, i);
10             }
11         }
12     }
13     
14     private void insert(String s, int index){
15         TrieNode p = root;
16         for(char c : s.toCharArray()){
17             if(p.nexts[c - 'a'] == null){
18                 p.nexts[c - 'a'] = new TrieNode();
19             }
20             
21             p = p.nexts[c - 'a'];
22             p.index = index;
23         }
24     }
25     
26     public int f(String prefix, String suffix) {
27         TrieNode p = root;
28         String s = suffix + "{" + prefix;
29         for(char c : s.toCharArray()){
30             if(p.nexts[c - 'a'] == null){
31                 return -1;
32             }
33             
34             p = p.nexts[c - 'a'];
35         }
36         
37         return p.index;
38     }
39 }
40 
41 class TrieNode{
42     int index;
43     TrieNode [] nexts;
44     public TrieNode(){
45         nexts = new TrieNode[27];
46     }
47 }
48 
49 /**
50  * Your WordFilter object will be instantiated and called as such:
51  * WordFilter obj = new WordFilter(words);
52  * int param_1 = obj.f(prefix,suffix);
53  */

 

posted @ 2021-03-05 15:06  Dylan_Java_NYC  阅读(161)  评论(0编辑  收藏  举报