clueless coding // TODO: be smarter

LeetCode Sentence Screen Fitting: CPP Solution



TL;DR Code Solution


int wordsTyping(vector<string>& sentence, int rows, int cols) {

    unordered_map<string, int> doneBefore;

    int currentWord = 0;
    int totalWordsWritten = 0;
    for (int rowNum = 0; rowNum < rows; rowNum++) {
        if (doneBefore.find(sentence[currentWord]) == doneBefore.end()) {
            int rowLength = 0;
            int pre = totalWordsWritten;
            string preWord = sentence[currentWord];
            while (rowLength + sentence[currentWord].size() <= cols) {
                rowLength += sentence[currentWord].size() + 1;
                currentWord = (currentWord + 1) % sentence.size();
                totalWordsWritten++;
            }
            doneBefore[preWord] = totalWordsWritten - pre;
        }
        else {
            totalWordsWritten += doneBefore[sentence[currentWord]];
            currentWord = (currentWord + doneBefore[sentence[currentWord]]) % sentence.size();
        }
    }

    return totalWordsWritten / sentence.size();

}