Simple C++ using std::sort and std::binary_search


  • 0
    class Solution{
    public:
        string replaceWords(vector<string>& dict, string sentence){
            string res="", word="";
            sort(dict.begin(), dict.end());
            istringstream is(sentence, ios_base::in);
            while(is >> word){
                bool replaced=false;
                for (int i=0; i < (int)word.size(); i++){
                    string sstr = word.substr(0, i+1);
                    if (binary_search(dict.begin(), dict.end(), sstr)){
                        res += sstr + " ";
                        replaced=true;
                        break;
                    }
                }
                if (!replaced){
                    res += word + " ";
                }
            }
            res.pop_back(); // remove last trailing whitespace
            return res;
        }
    };
    

Log in to reply
 

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