Sentence Screen Fitting in C++


Suppose we have a rows x cols screen and a sentence represented by a list of non-empty words, so we have to find how many times the given sentence can be fitted on the screen. There are certain properties −

  • A word will not be split into two lines.

  • The order of words in the sentence must not be changed.

  • There will be only one space between two words.

  • The total number of words in the sentence won't exceed 100.

  • The length of each word is greater than 0 but less than 10.

  • 1 ≤ rows, cols ≤ 20,000.

So if the input is like rows = 3 and cols = 6, and the sentence is [“a”, “bcd”, “e”], then the output will be 2.

To solve this, we will follow these steps −

  • Define a map dp, set ret := 0, n := size of sentence array

  • while row is not 0

    • start := ret mod n, len := -l and cnt := 0

    • if start is not present in dp, then

      • while 1 + len + size of sentence[(start + cnt) mod n] <= cols

        • len := 1 + len + sentence[(start + cnt) mod n]

        • increase cnt by 1

      • dp[start] := cnt

      • ret := ret + cnt

    • otherwise ret := ret + dp[start]

    • row := row – 1

  • return ret/n

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int wordsTyping(vector<string>& sentence, int rows, int cols) {
      unordered_map <int, int> dp;
      int ret = 0;
      int n = sentence.size();
      while(rows--){
         int start = ret % n;
         int len = -1;
         int cnt = 0;
         if(!dp.count(start)){
            while(1 + len + (int)sentence[(start + cnt) % n].size() <= cols){
               len = 1 + len + sentence[(start + cnt) % n].size();
               cnt++;
            }
            dp[start] = cnt;
            ret += cnt;
         }
         else{
            ret += dp[start];
         }
      }
      return ret / n;
   }
};
main(){
   vector<string> v = {"a","bcd","e"};
   Solution ob;
   cout << (ob.wordsTyping(v, 3, 6));
}

Input

["a","bcd","e"]
3
6

Output

2

Updated on: 29-Apr-2020

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements