Leetcode 68:文字左右對齊(超詳細的解法!!!)
阿新 • • 發佈:2018-12-15
給定一個單詞陣列和一個長度 maxWidth,重新排版單詞,使其成為每行恰好有 maxWidth 個字元,且左右兩端對齊的文字。
你應該使用“貪心演算法”來放置給定的單詞;也就是說,儘可能多地往每行中放置單詞。必要時可用空格 ' '
填充,使得每行恰好有 maxWidth 個字元。
要求儘可能均勻分配單詞間的空格數量。如果某一行單詞間的空格不能均勻分配,則左側放置的空格數要多於右側的空格數。
文字的最後一行應為左對齊,且單詞之間不插入額外的空格。
說明:
- 單詞是指由非空格字元組成的字元序列。
- 每個單詞的長度大於 0,小於等於 maxWidth。
- 輸入單詞陣列
words
示例:
輸入:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
輸出:
[
"This is an",
"example of text",
"justification. "
]
示例 2:
輸入: words = ["What","must","be","acknowledgment","shall","be"] maxWidth = 16 輸出: [ "What must be", "acknowledgment ", "shall be " ] 解釋: 注意最後一行的格式應為 "shall be " 而不是 "shall be", 因為最後一行應為左對齊,而不是左右兩端對齊。 第二行同樣為左對齊,這是因為這行只包含一個單詞。
示例 3:
輸入: words = ["Science","is","what","we","understand","well","enough","to","explain", "to","a","computer.","Art","is","everything","else","we","do"] maxWidth = 20 輸出: [ "Science is what we", "understand well", "enough to explain to", "a computer. Art is", "everything else we", "do " ]
解題思路
這個問題非常簡單,主要的難點在於邊界問題的思考。我們要分成如下幾個問題討論
- 當前行不是最後一行
- 當前行只能包含一個單詞
- 當前行可以容納多個單詞
- 當前行是最後一行
- 當前行只能包含一個單詞
- 當前行可以容納多個單詞
class Solution:
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
if not words:
return list()
res, row = list(), list()
words_len, count = len(words), 0
i = 0
while i < words_len:
if len(words[i]) + count <= maxWidth:
count += len(words[i]) + 1
row.append(words[i])
i += 1
continue
else:
if len(row) == 1:
res.append(str(row[0])+' '*(maxWidth - len(row[0])))
else:
extraSpace = maxWidth - count + len(row)
num_space = extraSpace//(len(row) - 1)
pre_space = extraSpace%(len(row) - 1)
tmp = ''
for word in row[:-1]:
if pre_space > 0:
tmp += str(word) + ' '*(num_space + 1)
pre_space -= 1
else:
tmp += str(word) + ' '*(num_space + 0)
tmp += str(row[-1])
res.append(tmp)
row.clear()
count = 0
tmp = ' '.join(row)
res.append(tmp + (maxWidth - len(tmp))*' ')
return res
非常簡單,只是要考慮更多的邊界問題而已。
我將該問題的其他語言版本新增到了我的GitHub Leetcode
如有問題,希望大家指出!!!