Skip to content

Commit 468b759

Browse files
committed
Sentence Screen Fitting
1 parent 6eec4d1 commit 468b759

File tree

2 files changed

+81
-1
lines changed

2 files changed

+81
-1
lines changed

058 Spiral Matrix II.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
]
1313
"""
1414
__author__ = 'Danyang'
15+
16+
1517
class Solution:
1618
def generateMatrix(self, n):
1719
"""
@@ -48,7 +50,8 @@ def generateMatrix(self, n):
4850

4951
return result
5052

53+
5154
if __name__=="__main__":
5255
result = Solution().generateMatrix(4)
5356
for row in result:
54-
print row
57+
print row

418 Sentence Screen Fitting.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#!/usr/bin/python3
2+
"""
3+
Given a rows x cols screen and a sentence represented by a list of non-empty
4+
words, find how many times the given sentence can be fitted on the screen.
5+
6+
Note:
7+
A word cannot be split into two lines.
8+
The order of words in the sentence must remain unchanged.
9+
Two consecutive words in a line must be separated by a single space.
10+
Total words in the sentence won't exceed 100.
11+
Length of each word is greater than 0 and won't exceed 10.
12+
1 ≤ rows, cols ≤ 20,000.
13+
Example 1:
14+
15+
Input:
16+
rows = 2, cols = 8, sentence = ["hello", "world"]
17+
18+
Output:
19+
1
20+
21+
Explanation:
22+
hello---
23+
world---
24+
25+
The character '-' signifies an empty space on the screen.
26+
Example 2:
27+
28+
Input:
29+
rows = 3, cols = 6, sentence = ["a", "bcd", "e"]
30+
31+
Output:
32+
2
33+
34+
Explanation:
35+
a-bcd-
36+
e-a---
37+
bcd-e-
38+
39+
The character '-' signifies an empty space on the screen.
40+
Example 3:
41+
42+
Input:
43+
rows = 4, cols = 5, sentence = ["I", "had", "apple", "pie"]
44+
45+
Output:
46+
1
47+
48+
Explanation:
49+
I-had
50+
apple
51+
pie-I
52+
had--
53+
54+
The character '-' signifies an empty space on the screen.
55+
"""
56+
from typing import List
57+
58+
59+
class Solution:
60+
def wordsTyping(self, sentence: List[str], rows: int, cols: int) -> int:
61+
"""
62+
How many times to fit
63+
64+
Combine the words in to a string and wrap it around
65+
"""
66+
sentence = " ".join(sentence) + " " # unify the condition checking for the last word; tail will wrap with head with space
67+
i = 0
68+
for r in range(rows):
69+
i += cols
70+
while sentence[i % len(sentence)] != " ":
71+
i -= 1
72+
73+
# now sentence[i] is " "
74+
i += 1
75+
76+
ret = i // len(sentence)
77+
return ret

0 commit comments

Comments
 (0)