zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):068-Text Justification

    题目来源:

      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

  • 相关阅读:
    Log4j---文件解析以及语法使用
    Sessions 与Cookies详解
    Web三大组件之控制器组件Servlet(转载)
    单向链表和双向链表
    单向队列和环形队列
    稀疏数组
    XML解析器之JAXP与DOM4J
    DTD约束与schema约束的不同
    XML之基础和DTD解析
    数据库----SQL基本查询
  • 原文地址:https://www.cnblogs.com/chruny/p/5045245.html
Copyright © 2011-2022 走看看