cur = len(words[i]) + 1 start = i res.append(" ".join(words[start:]).ljust(max_width, " ")) return res
# def fullJustify(self, words, maxWidth): deffull_justify(words, max_width):# ? 不用self,语法规范否? """ :type words: List[str] :type max_width: int :rtype: List[str] """ res = [] tmp = [] lg = 0 for i in words: if len(i) + lg <= max_width: tmp.append(i) lg += len(i) + 1 else: res.append(tmp) tmp = [i] lg = len(i) + 1 res.append(tmp) for word in res[:-1]: lg = sum(len(ws) for ws in word) if len(word) == 1: word[0] = word[0] + ' ' * (max_width - lg) else: while lg != max_width: for i in range(len(word) - 1): word[i] = word[i] + ' ' lg += 1 if lg == max_width: break ans = ' '.join(res[-1]) if len(ans) < max_width: ans = ans + " " * (max_width - len(ans)) # print(ans) return [''.join(word) for word in res[:-1]] + [ans]
if __name__ == "__main__": txt_list = [ "This is a sample textyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy for testing justification.", "This2 is a sa justification2.", "This3 is a sample texjustification2.", "This4 is a sample text forstification2.", "This5 is a saustification2.", ] txt_list = " ".join(txt_list).split(" ") max_len = 80 # ins = Solution() # for line in ins.fullJustify(txt_list, max_len): for line in Solution.full_justify(txt_list, max_len): print("[", line, "]") print(" ---" * 20) for line in Solution.full_justify2(txt_list, max_len): print("[", line, "]")