Given a rows x cols
screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen.
Note:
- A word cannot be split into two lines.
- The order of words in the sentence must remain unchanged.
- Two consecutive words in a line must be separated by a single space.
- Total words in the sentence won't exceed 100.
- Length of each word is greater than 0 and won't exceed 10.
- 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: I-had apple pie-I had-- The character '-' signifies an empty space on the screen.
----------------------------------------------------------------------------
这题目刚开始用循环节的思路搞了,非常容易写bug,代码如下:
class Solution:
def wordsTyping(self, sentence, rows: int, cols: int) -> int:
dic = {0: (0, 0)} # off:(linenumber,res)
x, y, res, idx, wl, flg = 0, 0, 0, 0, len(sentence), False
while (True):
l = len(sentence[idx])
if (l > cols):
return 0
newline = 0 if x + l <= cols else 1 # write cur word in new line
used = x + l + 1 if newline == 0 else l + 1
nx = used if used < cols else 0
ny = y + newline if used < cols else y + 1 + newline
if (ny > rows or (ny == rows and nx > 0)):
return res
idx, x, y = idx + 1, nx, ny
if (idx == wl):
res += 1
idx = 0
if (flg == False):
if (x in dic):
pline, pres = dic[x]
cycle = (rows - y -1) // (y - pline) #bug1: cycle = (rows - pline) // (y - pline)
#bug3: cycle = (rows - y) // (y - pline)
print("pline={0} pres={1} y={2} res={3} cycle={4}".format(pline,pres, y, res, cycle))
res += cycle * (res - pres)
y += cycle * (y - pline) #bug2: y += cycle * (rows - pline)
flg = True
dic[x] = (y, res)
后来在Discussion里发现了一种更好的思路:
把所有的词以空格分隔,假设可以拼成无限长度,那么问题就变成了每次给一行屏幕的宽度cols,展示一定数量的单词,这个off会到什么位置,最后off // len(拼起来的sentence)就是需要的结果
class Solution(object):
def wordsTyping(self, sentence, rows, cols):
s = ' '.join(sentence) + ' '
l = len(s)
off = 0
for i in range(rows):
off += cols
if (s[off % l] == ' '):
off += 1
else:
while (off > 0 and s[(off-1)%l] != ' '):
off -= 1
return off // l