Straight forward C++ solution


  • 0
    S
    class Solution {
    public:
        
        string replaceWords(vector<string>& dict, string sentence) {
            int l=sentence.length();
            vector<string> splits;
            string res;
            int i,j,k;
            for(i=0;i<l;) {
                for(j=i;j<l;j++) {
                    if(sentence[j]==' ') {
                        j++;
                        break;
                    }
                }
                if(j==l) {
                    splits.push_back(sentence.substr(i,j-i));
                } else {
                    splits.push_back(sentence.substr(i,j-i-1));
                }            
                i=j;
            }
            auto comp=[](const string& s1,const string& s2) {return s1.length()<s2.length();};
            sort(dict.begin(),dict.end(),comp);
            int ii=splits.size();
            int jj=dict.size();
            for(i=0;i<ii;i++) {
                for(j=0;j<jj;j++) {
                    if(splits[i].find(dict[j])==0) {
                        splits[i]=dict[j];
                        break;
                    }
                }
                res=res+splits[i];
                res.push_back(' ');
            }
            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.