My c++ solution by unordered_set


  • 0
    X

    using unordered_set(hash) to search

    class Solution {
    public:
        string replaceWords(vector<string>& dict, string sentence) {
            unordered_set<string> map;
            for(string s : dict)
                map.insert(s);
            string res = "";
            int len = sentence.size();
            if(!len) return res;
            string temp;
            bool fi;
            for(int i = 0; i < len; i++)
            {
                fi = false;
                temp = "";
                while(i < len && sentence[i] != ' ') 
                {
                    temp += sentence[i++];
                    if(!fi && map.count(temp))
                    {
                        res += temp + " ";
                        fi = true;
                    }
                }
                if(!fi) res += temp + " ";
            }
            res.pop_back();
            return res;
        }
    };
    

Log in to reply
 

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