Why is this problem labeled as hard? I don't see the point


  • 0
    C

    Just read more words until it exceeds the maxWidth and justify them.


  • 0
    C

    My Python solution

    class Solution(object):
        def fullJustify(self, words, maxWidth):
            """
            :type words: List[str]
            :type maxWidth: int
            :rtype: List[str]
            """
            def justify_line(lst, tlen):
                n = len(lst)
                if n == 1: return lst[0].ljust(maxWidth)
                sps_cnt = maxWidth - tlen
                sps_per = sps_cnt / (n-1) + 1
                sps_rem = sps_cnt % (n-1)
                r = ''
                for i in range(n-1):
                    if i < sps_rem:
                        r += lst[i] + ' ' * (sps_per+1)
                    else:
                        r += lst[i] + ' ' * (sps_per)
                r += lst[n-1]
                return r
            
            tlen, tlst, res = -1, [], []
            for word in words:
                tlen += len(word) + 1
                if tlen > maxWidth:
                    res.append(justify_line(tlst, tlen - len(word) - 1))
                    tlst = [word]
                    tlen = len(word)
                else:
                    tlst.append(word)
            if len(tlst) > 0:
                res.append(" ".join(tlst).ljust(maxWidth))
            return res
    

Log in to reply
 

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