C++ clear, straight-forward solution


  • 0
    M
        string replaceWords(vector<string>& dict, string sentence) {
            unordered_set<string> dic;
            for(int i=0;i<dict.size();i++) dic.insert(dict[i]);
            vector<string> s;
            string res, temp;
            for(int i=0;i<sentence.size();i++) {
                if(sentence[i]==' ') {
                    s.push_back(temp);
                    temp.clear();
                }
                else temp.append(1, sentence[i]);
            }
            s.push_back(temp);
            for(int i=0;i<s.size();i++) {
                string t;
                for(int j=0;j<s[i].size();j++) {
                    t.append(1, s[i][j]);
                    if(dic.find(t)!=dic.end()) {
                        res+=t+" ";
                        break;
                    }
                }
                if(dic.find(t)==dic.end()) res+=t+" ";
            }
            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.