首页 > 编程语言 > 详细

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

时间:2015-12-14 16:28:10      阅读:157      评论:0      收藏:0      [点我收藏+]

题目来源:

  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

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

原文:http://www.cnblogs.com/chruny/p/5045245.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!