forked from dmamaril/LeetCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
418. Sentence Screen Fitting.cpp
58 lines (41 loc) · 1.15 KB
/
418. Sentence Screen Fitting.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
time O(rows * word length)
space O(number of characters in the reformatted sentence) = O(number of words * word length)
Reformatted sentence
["ab", "cde", "f"] --> "ab cde f "
count: how many characters of the reformatted sentence is on the screen
count % length of reformatted sentence: the starting position of the next row
Answer: count / length of reformatted sentence
length: 9
count = (3 + 4 + 5 + 4 + 5) / 9 = 2
row 5
col 4
ab cde f ab cde f ab cde f....
XXX
XXXX
XXXXX
XXXX
XXXXX
*/
class Solution {
public:
int wordsTyping(vector<string>& sentence, int rows, int cols) {
string s;
for (const auto& sen: sentence) {
s += sen;
s += " ";
}
int count{0};
int n = s.size();
for (int i = 0; i < rows; ++i) {
count += cols;
if (s[count % n] == ' ') {
++count;
} else {
while (count > 0 && s[(count - 1) % n] != ' ')
--count;
}
}
return count / n;
}
};