Advertisement
nikunjsoni

418

Jun 7th, 2021
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int wordsTyping(vector<string>& sentence, int rows, int cols) {
  4.         unordered_map<int, int> umap;
  5.         int num = 0, n = sentence.size();
  6.        
  7.         // Each row will start with some word.
  8.         // So better maintain a map that if we start from word x, we will cover cnt number of words.
  9.         // Count the total number of words that can be fit in the given rows, divide it by number of
  10.         // words in sentence to get number of lines required.
  11.         for(int i = 0; i < rows; i++){
  12.             int start = num % n;
  13.             if(umap.count(start) == 0){
  14.                 int cnt = 0, len = 0;
  15.                 for(int i = start; len < cols; i = (i+1) % n, cnt++){
  16.                     if(len + sentence[i].size() > cols)
  17.                         break;
  18.                     len += sentence[i].size() + 1;
  19.                 }
  20.                 num += cnt;
  21.                 umap.emplace(start, cnt);
  22.             }
  23.             else
  24.                 num += umap[start];
  25.         }
  26.         return num / n;
  27.     }
  28. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement