Text Justification
这道题对字符串之间的空格调整是个非常复杂的逻辑,可以说这个题如果面试之前没准备过直接写出来没bug的可能性极低,discussion里面给的Python答案只用了一行代码就处理了空格添加的问题,而且方法很容易理解,有点类似任务分配算法里面的round-robin,此题要写出这样的代码很难,不过理解之后再背下来问题不大
class Solution(object):
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
result, curWords, countOfLetters = [], [], 0
for word in words:
if countOfLetters + len(curWords) + len(word) > maxWidth: # 当前词加上一个空格已经超过当前行的限制了
# round-robin,每两个词之间按照顺序逐个加空格,或1是为了防止有一个词占一行的情况
for i in xrange(maxWidth - countOfLetters):
curWords[(i % (len(curWords) - 1 or 1))] += ' '
result.append(''.join(curWords))
curWords, countOfLetters = [], 0
curWords.append(word)
countOfLetters += len(word)
return result + [' '.join(curWords).ljust(maxWidth)] # 最后一排的词是还未处理的