clueless coding // TODO: be smarter

LeetCode Replace Words: CPP Solution



TL;DR Code Solution


string formSentence(vector<string>& sentence) {
    string result;
    for (int i = 0; i < sentence.size(); i++) {
        if (i != 0) {
            result += ' ';
        }
        result += sentence[i];
    } 
    return result;
}

string replaceWords(vector<string>& dict, string sentence) {
    vector<string> newSentence;
    unordered_map<string, bool> map;

    string current;
    for (int i = 0; i < sentence.length(); i++) {
        if (sentence[i] != ' ') {
            current += sentence[i];
        }

        if (sentence[i] == ' ' || i == (int)sentence.length() - 1) {
            newSentence.push_back(current);
            current = "";
        }
    }

    for (int i = 0; i < dict.size(); i++) {
        map[dict[i]] = true;
    }

    for (int i = 0; i < newSentence.size(); i++) {
        string current;
        for (int j = 0; j < newSentence[i].length(); j++) {
            current += newSentence[i][j];
            if (map.find(current) != map.end()) {
                newSentence[i] = current;
                break;
            }
        }
    }

    return formSentence(newSentence);
}