Sentence Screen Fitting

medium string dp

Problem

Given a screen with rows rows and cols columns, and an array of words sentence, return how many times the sentence fits on the screen end-to-end.

Inputrows = 2, cols = 8, sentence = ["hello","world"]
Output1
"hello world" fits once across the two rows.

def words_typing(sentence, rows, cols):
    s = " ".join(sentence) + " "
    n = len(s)
    p = 0
    for _ in range(rows):
        p += cols
        while p > 0 and s[p % n] != " ":
            p -= 1
        p += 1
    return p // n
function wordsTyping(sentence, rows, cols) {
  const s = sentence.join(" ") + " ";
  const n = s.length;
  let p = 0;
  for (let i = 0; i < rows; i++) {
    p += cols;
    while (p > 0 && s[p % n] !== " ") p--;
    p++;
  }
  return Math.floor(p / n);
}
class Solution {
    public int wordsTyping(String[] sentence, int rows, int cols) {
        String s = String.join(" ", sentence) + " ";
        int n = s.length(), p = 0;
        for (int i = 0; i < rows; i++) {
            p += cols;
            while (p > 0 && s.charAt(p % n) != ' ') p--;
            p++;
        }
        return p / n;
    }
}
int wordsTyping(vector& sentence, int rows, int cols) {
    string s;
    for (auto& w : sentence) s += w + " ";
    int n = s.size(), p = 0;
    for (int i = 0; i < rows; i++) {
        p += cols;
        while (p > 0 && s[p % n] != ' ') p--;
        p++;
    }
    return p / n;
}
Time: O(rows) Space: O(L)