Simple C++ Solution (Easily Understood)

  • 0
    class MagicDictionary {
        set<string> myDict;
        /** Initialize your data structure here. */
        MagicDictionary() {
        /** Build a dictionary through a list of words */
        void buildDict(vector<string> dict) {
            for(auto c: dict)
        /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
        bool search(string word) {
            for(auto it = myDict.begin(); it != myDict.end(); it++){
                int diffCnt = 0;
                //if words aren't same size, no need to check word
                if(it->size() == word.size()){
                    //since they're same size, create copy of both words so you can sort and easily compare character for character at each index to see how many characters differ
                    string temp1 = *it;
                    string temp2 = word;
                    for (int i = 0; i < word.size(); i++)
                        if ( temp1[i] != temp2[i])
                //if you have found one possible word no need to look further
                if (diffCnt == 1) return true;
            return false;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.