# 418. Sentence Screen Fitting

Given a `rows x cols` screen and a sentence represented by a list of words, find how many times the given sentence can be fitted on the screen.

Note:

1. A word cannot be split into two lines.
2. The order of words in the sentence must remain unchanged.
3. Two consecutive words in a line must be separated by a single space.
4. Total words in the sentence won’t exceed 100.
5. Length of each word won’t exceed 10.
6. 1 ≤ rows, cols ≤ 20,000.

Example 1:

``````Input:
rows = 2, cols = 8, sentence = ["hello", "world"]

Output:
1

Explanation:
hello---
world---

The character '-' signifies an empty space on the screen.
``````

Example 2:

``````Input:
rows = 3, cols = 6, sentence = ["a", "bcd", "e"]

Output:
2

Explanation:
a-bcd-
e-a---
bcd-e-

The character '-' signifies an empty space on the screen.
``````

Example 3:

``````Input:
rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"]

Output:
1

Explanation:
apple
pie-I

The character '-' signifies an empty space on the screen.
``````

``````class Solution {
public:
int wordsTyping(vector<string>& sentence, int rows, int cols) {
string all = "";
for (string word : sentence) all += (word + " ");
int start = 0, len = all.size();
for (int i = 0; i < rows; ++i) {
start += cols;
if (all[start % len] == ' ') {
++start;
} else {
while (start > 0 && all[(start - 1) % len] != ' ') {
--start;
}
}
}
return start / len;
}
};
``````

``````class Solution {
public:
int wordsTyping(vector<string>& sentence, int rows, int cols) {
string all = "";
for (string word : sentence) all += (word + " ");
int res = 0, idx = 0, n = sentence.size(), len = all.size();
for (int i = 0; i < rows; ++i) {
int colsRemaining = cols;
while (colsRemaining > 0) {
if (sentence[idx].size() <= colsRemaining) {
colsRemaining -= sentence[idx].size();
if (colsRemaining > 0) colsRemaining -= 1;
if (++idx >= n) {
res += (1 + colsRemaining / len);
colsRemaining %= len;
idx = 0;
}
} else {
break;
}
}
}
return res;
}
};
``````

https://leetcode.com/problems/sentence-screen-fitting/

https://leetcode.com/problems/sentence-screen-fitting/discuss/90849/accepted-java-solution

https://leetcode.com/problems/sentence-screen-fitting/discuss/90845/21ms-18-lines-java-solution

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation