Guest User

Leetcode - 418

a guest
May 18th, 2021
359
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. class Solution {
  2.     int nWords, completions;
  3.     int getNextInd(int startInd, vector<int>& cumSentLen, int cols) {
  4.         int remSpace = cols;
  5.         int maxEnd;
  6.  
  7.         if(startInd > 0) {
  8.             int remLine = cumSentLen[nWords-1] - cumSentLen[startInd-1] - 1;
  9.             if(remLine <= remSpace) {
  10.                 remSpace -= remLine;
  11.                 startInd = 0;
  12.                 completions++;
  13.                 remSpace--;
  14.                 if(remSpace <= 0) return startInd;
  15.             } else {
  16.                 maxEnd = remSpace + cumSentLen[startInd-1] + 1;
  17.                 auto it = upper_bound(cumSentLen.begin(), cumSentLen.end(), maxEnd);
  18.                 return it - cumSentLen.begin();
  19.             }
  20.         }
  21.        
  22.         int newComp = remSpace/(cumSentLen[nWords-1] + 1);
  23.         completions += newComp;
  24.         remSpace -= (cumSentLen[nWords-1] + 1)*newComp;
  25.         if(remSpace == cumSentLen[nWords-1]) {
  26.             completions++;
  27.             remSpace = 0;
  28.             return startInd;
  29.         }
  30.        
  31.         auto it = upper_bound(cumSentLen.begin(), cumSentLen.end(), remSpace);
  32.         return it - cumSentLen.begin();
  33.     }
  34. public:
  35.     int wordsTyping(vector<string>& sentence, int rows, int cols) {
  36.         nWords = sentence.size();
  37.         completions = 0;
  38.         vector<int> cumSentLen(nWords, 0);
  39.         int lastSum = 0;
  40.         for(int i = 0; i < nWords; i++) {
  41.             if(i > 0) lastSum = cumSentLen[i-1] + 1;
  42.             cumSentLen[i] = lastSum + sentence[i].length();
  43.         }
  44.        
  45.         int nextInd = 0;
  46.         for(int i = 0; i < rows; i++) {
  47.             nextInd = getNextInd(nextInd, cumSentLen, cols);
  48.         }
  49.         return completions;
  50.     }
  51. };
Advertisement
Add Comment
Please, Sign In to add comment