Skip to content

LC 0068 [H] Text Justification

Code with Senpai edited this page May 18, 2022 · 1 revision
class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        res = []
        
        i = 0
        width = 0
        line = []
        
        while i < len(words): # so we can increment i to move to next word when ready
            word = words[i]
            
            if width + len(word) <= maxWidth: # word fits in line
                line.append(word)
                width += len(word) + 1 # include at least 1 space after each word
                i += 1 # move on to next word

            else: # done with words for a line, now justify spaces
                spaces = maxWidth - width + len(line) # number of spaces to add to fill up the line

                added = 0
                j = 0 # increment j to move to next word

                while added < spaces:
                    if j >= len(line) - 1:
                        j = 0        

                    line[j] += " " # add to the end of a word

                    added += 1
                    j += 1

                res.append("".join(line))
                line = [] # reset for next line
                width = 0
            
        # last line remains when loop exits, so handle it separately
        for word in range(len(line) - 1):
            line[word] += " " # at least 1 space between words
        line[-1] += " " * (maxWidth - width + 1) # +1 for the extra space above, remaining spaces to fill up the rest of the line, justify left, so just add spaces to right of last word
        res.append("".join(line))
        
        return res
Clone this wiki locally