Implement Magic Dictionary

刪除給定字符串的一個字符以後,可否在字典中找到刪除一個字符以後相等的值

問題:ui

Implement a magic directory with buildDict, and search methods.this

For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary.spa

For the method search, you'll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified word is in the dictionary you just built.code

Example 1:索引

Input: buildDict(["hello", "leetcode"]), Output: Null
Input: search("hello"), Output: False
Input: search("hhllo"), Output: True
Input: search("hell"), Output: False
Input: search("leetcoded"), Output: False

Note:ip

  1. You may assume that all the inputs are consist of lowercase letters a-z.
  2. For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest.
  3. Please remember to RESET your class variables declared in class MagicDictionary, as static/class variables are persisted across multiple test cases. Please see here for more details.

解決:ci

①  leetcode

  • 對於字典中的每一個單詞,每一個字符,刪除字符並將單詞的其他部分做爲關鍵字,將刪除的字符和字符的下標做爲值列表的一部分放入map中。
  • 例如:「hello」 -> {「ello」:[[0, ‘h’]], 「hllo」:[[1, ‘e’]], 「helo」:[[2, ‘l’],[3, ‘l’]], 「hell」:[[4, ‘o’]]}
  • 在查找過程當中,如步驟1所示生成key。當鍵值對中有一對相同的index但char不一樣時,返回true。 例如「healo」當刪除一個鍵時,鍵是「helo」,而且有一個索引相同但char不一樣的[2,'l'],則返回true。

class MagicDictionary { //141ms
    Map<String,List<int[]>> map = new HashMap<>();
    /** Initialize your data structure here. */
    public MagicDictionary() {}
    /** Build a dictionary through a list of words */
    public void buildDict(String[] dict) {
        for (String s : dict){
            for (int i = 0;i < s.length();i ++){
                String key = s.substring(0,i) + s.substring(i + 1);
                int[] pair = new int[]{i,s.charAt(i)};
                List<int[]> val = map.getOrDefault(key,new ArrayList<>());
                val.add(pair);
                map.put(key,val);
            }
        }
    }
    /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
    public boolean search(String word) {
        for (int i = 0;i < word.length();i ++){
            String key = word.substring(0,i) + word.substring(i + 1);
            if (map.containsKey(key)){
                for (int[] pair : map.get(key)){
                    if (pair[0] == i && pair[1] != word.charAt(i)){
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
/**
 * Your MagicDictionary object will be instantiated and called as such:
 * MagicDictionary obj = new MagicDictionary();
 * obj.buildDict(dict);
 * boolean param_2 = obj.search(word);
 */ rem

② 使用前綴樹實現。字符串

class MagicDictionary { //106ms     class TrieNode{         TrieNode[] children = new TrieNode[26];         boolean isWord = false;     }     TrieNode root;     /** Initialize your data structure here. */     public MagicDictionary() {         root = new TrieNode();     }     /** Build a dictionary through a list of words */     public void buildDict(String[] dict) {         for (String word : dict){             TrieNode cur = root;             for (char c : word.toCharArray()){                 int i = c - 'a';                 if (cur.children[i] == null) cur.children[i] = new TrieNode();                 cur = cur.children[i];             }             cur.isWord = true;         }     }     /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */     public boolean search(String word) {         return search(root,word.toCharArray(),0,0);     }     public boolean search(TrieNode root,char[] word,int start,int changed){         if (start == word.length) return root.isWord && changed == 1;         int index = word[start] - 'a';         for (int i = 0;i < 26;i ++){             if (root.children[i] == null) continue;             if (i == index){                 if (search(root.children[i],word,start + 1,changed)) return true;             }else {                 if (changed == 0 && search(root.children[i],word,start + 1,changed + 1)) return true;             }         }         return false;     } } /**  * Your MagicDictionary object will be instantiated and called as such:  * MagicDictionary obj = new MagicDictionary();  * obj.buildDict(dict);  * boolean param_2 = obj.search(word);  */

相關文章
相關標籤/搜索