Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class MagicDictionary {
- public:
- /** Initialize your data structure here. */
- unordered_map<string, int> sets;
- MagicDictionary() {
- }
- /** Build a dictionary through a list of words */
- void buildDict(vector<string> dict) {
- for(int i = 0; i < dict.size(); i++)
- {
- sets[dict[i]]++;
- for(int j = 0; j < dict[i].size(); j++)
- {
- char c = dict[i][j];
- dict[i][j] = '*';
- sets[dict[i]]++;
- dict[i][j] = c;
- }
- }
- }
- /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
- bool search(string word) {
- if(sets.find(word) != sets.end())
- {
- for(int i = 0; i < word.size(); i++)
- {
- char c = word[i];
- word[i] = '*';
- sets[word]--;
- word[i] = c;
- }
- }
- string temp = word;
- for(int i = 0; i < word.size(); i++)
- {
- char c = word[i];
- word[i] = '*';
- if(sets[word] > 0 )
- return true;
- word[i] = c;
- }
- word = temp;
- if(sets.find(word) != sets.end())
- {
- for(int i = 0; i < word.size(); i++)
- {
- char c = word[i];
- word[i] = '*';
- sets[word]++;
- word[i] = c;
- }
- }
- return false;
- }
- };
- /**
- * Your MagicDictionary object will be instantiated and called as such:
- * MagicDictionary* obj = new MagicDictionary();
- * obj->buildDict(dict);
- * bool param_2 = obj->search(word);
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement