1 Star 0 Fork 0

蓝桥云课/python-100

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
097-sentence_fit.py 1.30 KB
一键复制 编辑 原始数据 按行查看 历史
xiaoyi733112 提交于 2020-03-30 16:23 . python-100 answer
class Solution(object):
def count_sentence_fit(self, sentence, rows, cols):
if sentence is None:
raise TypeError('sentence cannot be None')
if rows is None or cols is None:
raise TypeError('rows and cols cannot be None')
if rows < 0 or cols < 0:
raise ValueError('rows and cols cannot be negative')
if cols == 0 or not sentence:
return 0
curr_row = 0
curr_col = 0
count = 0
while curr_row < cols:
for word in sentence:
# If the current word doesn't fit on the current line,
# move to the next line
if len(word) > cols - curr_col:
curr_col = 0
curr_row += 1
# If we are beyond the number of rows, return
if curr_row >= rows:
return count
# If the current word fits on the current line,
# 'insert' it here
if len(word) <= cols - curr_col:
curr_col += len(word) + 1
# If it still doesn't fit, then the word is too long
# and we should just return the current count
else:
return count
count += 1
return count
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/lanqiao-courses/python-100.git
git@gitee.com:lanqiao-courses/python-100.git
lanqiao-courses
python-100
python-100
master

搜索帮助