Python Solution, a little wordy though


  • 0
    class Solution(object):
        def fullJustify(self, words, maxWidth):
            def gets(s):
                ws = s.split(' ')
                if len(ws) == 1:
                    return ws[0] + ' ' * (maxWidth - len(ws[0]))
                spacecnt = len(ws) - 1
                wl = len(s) - spacecnt
                space = maxWidth - wl
                aspace, remainder = space / spacecnt, space % spacecnt
                ans = ''
                for w in ws:
                    ans += w
                    if spacecnt:
                        ans += ' ' * aspace
                        spacecnt -= 1
                    if remainder:
                        ans += ' '
                        remainder -= 1
                return ans
    
            def last(s):
                return s + ' ' * (maxWidth - len(s))
                
            if not maxWidth:
                return ['']
            idx = 0
            ans = []
            words = ' '.join(words) + ' '
            while idx + maxWidth < len(words):
                pre = idx
                idx += maxWidth - 1
                if words[idx] == ' ':
                    sub = words[pre: idx]
                elif words[idx + 1] == ' ':
                    sub = words[pre: idx + 1]
                    idx += 1
                else:
                    while words[idx] != ' ':
                        idx -= 1
                    sub = words[pre: idx]
                ans.append(gets(sub))
                idx += 1
            if idx < len(words):
                ans.append(last(words[idx: -1]))
            return ans
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.