Implement a magic directory buildDict
with, and search
methods.
For the method, you'll be buildDict
given a list of non-repetitive words to build a dictionary.
For the method, you'll be search
given a word, and judge whether if you modify exactly one character into another character In this word, the modified word are in the dictionary you just built.
Example 1:
Input:builddict (["Hello", "Leetcode"]), Output:NullInput:search ("Hello"), Output:FalseInput:search ("Hhllo"), Output:TrueInput:search ("Hell"), Output:FalseInput:search ("leetcoded"), Output:false
Note:
- You may assume this all the inputs is consist of lowercase letters
a-z
.
- For contest purpose, the test data was rather small by now. You could think about highly efficient algorithm after the contest.
- Remember to RESET your class variables declared in Class magicdictionary, as Static/class variables is persisted a Cross multiple test cases. Please see this for more details.
Implement a Magic dictionary that contains the builddict and search functions. The function of the BUILDDICT function is to create a dictionary of the given list of words without duplicates, and the function of the search function is to return true only if the character of the word has only one position, or false otherwise.
Java:
Class Magicdictionary {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 (St Ring[] dict) {for (string s:dict) {for (int i = 0; i < s.length (); i++) {string k EY = s.substring (0, I) + s.substring (i + 1); int[] pair = new int[] {i, S.charat (i)}; List<int[]> val = Map.getordefault (Key, New arraylist<int[]> ()); 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++) {St Ring 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; }}
Python:
Class Magicdictionary (object): def _candidates (self, word): For i in xrange (Len (Word)): yield word[:i] + ' * ' + word[i+1:] def builddict (self, words): self.words = set (words) self.near = collections. Counter (cand for word in words for cand in Self._candidates (word)) def search (self, word): return any ( Self.near[cand] > 1 or self.near[cand] = = 1 and Word not in self.words for cand in Self._candidates (word))
Python:
# Time:o (n), n is the length of the word# space:o (d) Import Collectionsclass magicdictionary (object): Def __init__ (SE LF): "" "Initialize your data structure here. "" "_trie = Lambda:collections.defaultdict (_trie) Self.trie = _trie () def builddict (Self, Dictionary): "" "Build a dictionary through a list of Words:type Dictionary:list[str]: rtype:void "" For word in dictionary:reduce (dict.__getitem__, Word, Self.trie). SetDefault ("_end") def search (s Elf, Word): "" "Returns if there is any word in the trie that equals to the given word after modifying exact Ly one Character:type word:str:rtype:bool "" "Def find (Word, curr, I, mistakeallowed): if i = = Len (word): Return "_end" in Curr and not mistakeallowed if word[i] not in Curr: return any (find (Word, curr[c], i+1, False) for C in Curr if c! = "_end") if mistakeallowed else False if Mistakeallowed:return find ( Word, curr[word[i]], i+1, True) or any (find (Word, curr[c], i+1, False) F or C in Curr if C isn't in ("_end", Word[i])) return find (Word, curr[word[i]], i+1, False) return to find (wor D, Self.trie, 0, True)
C++:
Class Magicdictionary {public: /** Initialize your data structure here. * /Magicdictionary () {} /** Build a di Ctionary through a list of words * /void Builddict (Vector<string> dict) {for (string word:dict) { m[w Ord.size ()].push_back (Word); } } /** Returns If there is any word in the trie, equals to the given word after modifying exactly one character */ Bo OL Search (string word) { for (string Str:m[word.size ()]) { int cnt = 0, i = 0; for (; i < word.size (); ++i) { if (word[i] = = Str[i]) continue; if (word[i]! = Str[i] && cnt = = 1) break; ++cnt; } if (i = = word.size () && cnt = = 1) return true; return false; } Private: unordered_map<int, vector<string>> m;};
C++:
Class Magicdictionary {public: /** Initialize your data structure here. * /Magicdictionary () {} /** Build a di Ctionary through a list of words */ void builddict (Vector<string> dict) {for (string word:dict) S.insert ( word); } /** Returns If there is any word in the trie, equals to the given word after modifying exactly one character */ Bo OL Search (string word) {for (int i = 0; i < word.size (); ++i) { char t = word[i]; for (char c = ' a '; c <= ' z '; ++c) { if (c = = t) continue; Word[i] = C; if (S.count (word)) return true; } Word[i] = t; } return false; } Private: unordered_set<string> s;};
Similar topics:
[Leetcode] 208. Implement Trie (Prefix tree) implements a dictionary tree (prefix trees)
720. Longest Word in Dictionary
[Leetcode] 676. Implement Magic Dictionary implements the Magic Dictionary