https://leetcode.com/problems/text-justification/

https://leetcode.com/problems/text-justification/

思路是这样的:

1.先分行

2.将这一行输出 

分行的方法是 前i个字符串和i-1个空格的长度小于Max  i自加

如果除了这i个字符串没有别的了 就用last()方法输出(输出最后一行的方法)

如果还有后续字符 就用 output()方法输出

判断是否为最后一行用了needle变量

每次分完一行 就将分完的删掉 所以 只要words[]还有内容 就要一直重复分行 

 

class Solution:
    # @param {string[]} words
    # @param {integer} maxWidth
    # @return {string[]}
    def output(self,words,temp,maxWidth):
        alllength=0
        newstring=''
        n=0
        average=0
        extra=0
        for i in words[0:temp+1]:
            alllength=alllength+len(i)
        if temp!=0:
            average=(maxWidth-alllength)/temp
            extra=(maxWidth-alllength)%temp
        if temp==0:
            newstring=words[0]+' '*(maxWidth-len(words[0]))
        else:
            for i in words[0:temp]:
                newstring=newstring+i+' '*average
                if n<extra:
                    newstring=newstring+' '
                    n=n+1
            newstring=newstring+words[temp]
        return newstring
        
        
    def last(self,words,maxWidth):
        lastline=''
        if maxWidth==len(words[0]):
            return words[0]
        for i in words:
            lastline=lastline+i+' '
        n=len(lastline)
        lastline=lastline+(maxWidth-n)*' '
        return lastline    
        
    def fullJustify(self, words, maxWidth):
        sol=[]
        temp=0
        lastline=''
        if len(words)==1:
            lastline=Solution().last(words,maxWidth)
            sol.append(lastline)
            return sol
        else:
            while len(words)>0:
                temp=0
                length=len(words[0])
                all=0
                needle=0
                while length+temp<=maxWidth:
                    if temp!=len(words)-1:
                        temp=temp+1
                        length=length+len(words[temp])
                    else:#temp为最后一个的index
                        needle=1
                        break
                if needle==0:
                    temp=temp-1
                    sol.append(Solution().output(words,temp,maxWidth))
                    words=words[temp+1:]
                else:
                    lastline1=''
                    lastline1=Solution().last(words,maxWidth)
                    sol.append(lastline1)
                    break
            return sol


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值