C++ set solution


  • 0
    M
    class Solution {
    public:
        string replaceWords(vector<string>& dict, string sentence) {
            unordered_set<string> s;
            for(auto it : dict)
            {
                s.insert(it);
            }
            string res = "";
            //two pointers 
            for(int i = 0; i < sentence.size(); i++)
            {
                if(sentence[i] == ' ')
                {
                    res.push_back(sentence[i]);
                    continue;
                }
                int j = i;
                bool isPrefix = false;
                while(j < sentence.size() && sentence[j] != ' ')
                {
                    if(s.find(sentence.substr(i, j - i + 1)) != s.end())
                    {
                        res += sentence.substr(i, j - i + 1);
                        isPrefix = true;
                        while(j < sentence.size() && sentence[j] != ' ')j++;
                        break;
                    }
                    else
                    {
                        j++;
                    }
                }
                if(!isPrefix)res += sentence.substr(i, j - i);
                i = j - 1;
                
            }
            return res;
        }
    };

Log in to reply
 

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