Question: https://oj.leetcode.com/problems/text-justification/
Question Name: Text Justification
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | class Solution: # @param words, a list of strings # @param L, an integer # @return a list of strings def fullJustify(self, words, L): begin, end = 0, 0 # The index of begin word (inclusive) and end # word (exclusive) in one line result =[] while True: wordsLen = 0 # The total length of all words to be used # in this line. # Determine how many following words are used for this line. while end < len(words): if wordsLen + len(words[end]) + (end - begin) <= L: wordsLen += len(words[end]) end += 1 else: break else: # This is the last line. temp = " ".join(words[begin:end]) temp += " " * (L - len(temp)) result.append(temp) break # Construct the line after text justification. temp = "" if end == begin + 1: # This line only contains one word. temp = words[begin] + " " * (L - len(words[begin])) else: # This line contains multiple words. spaceCount = (L - wordsLen) // (end - begin -1) oneMoreSpace = (L- wordsLen) % (end- begin - 1) for index in xrange(begin, end-1): if index - begin < oneMoreSpace: temp += words[index] + " " * (spaceCount + 1) else: temp += words[index] + " " * spaceCount temp += words[end-1] result.append(temp) begin = end return result |