Posted on 2023-08-24 18:57
Uriel 阅读(28)
评论(0) 编辑 收藏 引用 所属分类:
模拟 、
闲来无事重切Leet Code
模拟word的两端对齐排版(最后一行不用对齐),模拟题
1 #68
2 #Runtime: 14 ms (Beats 75.43%)
3 #Memory: 13.3 MB (Beats 67.24%)
4
5 class Solution(object):
6 def fullJustify(self, words, maxWidth):
7 """
8 :type words: List[str]
9 :type maxWidth: int
10 :rtype: List[str]
11 """
12 p = 0
13 ans = []
14 n_sp = []
15 while p < len(words):
16 tp = [words[p]]
17 l = len(words[p])
18 p += 1
19 while p < len(words) and l + len(words[p]) + 1 <= maxWidth:
20 l += len(words[p]) + 1
21 tp.append(words[p])
22 p += 1
23 n_sp = maxWidth - l
24 tp_ans = ""
25 if len(tp) == 1:
26 tp_ans += tp[0] + " " * n_sp
27 else:
28 if p == len(words):
29 for i in range(len(tp) - 1):
30 tp_ans += tp[i] + " "
31 tp_ans += tp[-1]
32 for _ in range(n_sp):
33 tp_ans += " "
34 else:
35 for i in range(len(tp) - 1):
36 tp_ans += tp[i] + " " * (1 + n_sp // (len(tp) - 1))
37 if (n_sp % (len(tp) - 1)) > i:
38 tp_ans += " "
39 tp_ans += tp[-1]
40 ans.append(tp_ans)
41 return ans