LeetCode T68

Insert picture description here
Insert picture description here

class Solution:
    def fullJustify(self,words, maxWidth):
        n = len(words)
        result = []
        if n == 1:
            result.append(words[0] + " "*(maxWidth - len(words[0])))
            return result
        count=0
        while(count < n):
            string = ''
            wordCount = 0
            begin = count
            while(count < n ):
                string += words[count]
                wordCount +=1
                count +=1
                if count < n:
                    if len(string)+ len(words[count]) + wordCount > maxWidth:
                        break

            if count==n:
                if wordCount >1:
                    n_empty = maxWidth - len(string)
                    string = ''
                    for i in range(begin,begin+wordCount-1):
                        string+=words[i]
                        string+=' '
                        n_empty -=1
                    string += words[begin+wordCount - 1]
                    string+=(n_empty*' ')

                    result.append(string)
                else:
                    result.append(words[begin] + (maxWidth-len(words[begin]))*' ')
                return result

            if wordCount >1:
                
                n_empty = maxWidth - len(string)
                mod = n_empty%(wordCount - 1)
                x = int(n_empty/(wordCount - 1))

                string = ''
                for i in range(begin,begin+wordCount):
                    string+=words[i]
                    if i!=begin+wordCount-1:
                        if mod!=0:
                            string+=' '
                            mod-=1
                        string += ' '*x

                result.append(string)
            else:
                result.append(words[begin] + (maxWidth-len(words[begin]))*' ')

Insert picture description here

Guess you like

Origin blog.csdn.net/wjl__ai__/article/details/112340867