leetcode解题笔记-Text Justification

原题地址:https://oj.leetcode.com/problems/text-justification/

题目大致意思是:给定一个字符串数组,和一个整数L,把这个字符串按一定形式输出。

题目比较简单,也没什么特别的算法。直接给出代码。

class Solution:
    # @param words, a list of strings
    # @param L, an integer
    # @return a list of strings
    def fullJustify(self, words, L):
        if L==0:
            return [""]
        lines = []
        start,count = 0,0
        line = ""
        for i in range(0,len(words)):
            if (count + (len(words[i])+1))<=L+1:
                count += len(words[i])+1
            else:
                space = L-(count-i+start)
                for j in range(start,i):
                    if space == 0 or i-start==1:
                        line += words[j] + space*" "
                    elif space == space//(i-1-j)*(i-1-j):
                        line += words[j] + space/(i-1-j)*" "
                        space -= space/(i-1-j)
                    else:
                        line += words[j] + (space//(i-1-j)+1)*" "
                        space -= space//(i-1-j)+1
                lines.append(line)
                start = i
                line = ""
                count = len(words[i])+1
        if count != 0:
            line = " ".join(words[start::])
            lines.append( line + (L-len(line))*" ")
        print lines
Solution().fullJustify([""], 2)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值