[LeetCode]题解(python):068-Text Justification

本文介绍了一个文本对齐算法,该算法能够将输入的字符串数组按照规定的长度进行对齐,并通过合理的空格填充来确保每行文本的美观。文章提供了一段Python代码实现,详细解析了如何处理字符串数组以达到文本对齐的效果。

题目来源:

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


 

题意分析:

  输入一个字符串数组和一个规定长度L。将这个字符串数组的元素尽可能放到长度的L的字符串中,数组中的字符串不能拆开,一个长度L的字符串包括的若干个字符串之间用相等的空格间隔开。比如:

words: ["This", "is", "an", "example", "of", "text", "justification."],L: 16.

将返回

[
   "This    is    an",
   "example  of text",
   "justification.  "
]

 

题目思路:

  这道题目直接模拟解就可以了,要注意的是有很多细节要处理。从开始加入元素,长度增加,然后空格+1后继续加入新元素,直到长度大于L。然后判断空格的个数就可以了。


 

代码(Python):

  

class Solution(object):
    def fullJustify(self, words, maxWidth):
        """
        :type words: List[str]
        :type maxWidth: int
        :rtype: List[str]
        """
        ans = []
        i = 0
        while i < len(words):
            size,begin = 0,i
            while i < len(words):
                if size == 0:
                    newsize = len(words[i])
                else:
                    newsize = size + len(words[i]) + 1
                if newsize <= maxWidth:
                    size = newsize
                else:
                    break
                i += 1
            s = maxWidth - size
            if i - begin - 1 > 0 and i < len(words):
                ns = s / (i - begin - 1)
                s %= i - begin - 1
            else:
                ns = 0
            j = begin
            while j < i:
                if j == begin: tmp = words[j]
                else:
                    tmp += ' '*(ns + 1)
                    if s > 0 and i < len(words):
                        tmp += ' '
                        s -= 1
                    tmp += words[j]
                j += 1
            tmp += ' '*s
            ans.append(tmp)
        return ans
View Code

 


 

转载请注明出处:http://www.cnblogs.com/chruny/p/5045245.html

转载于:https://www.cnblogs.com/chruny/p/5045245.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值