题目来源:
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):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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
转载请注明出处:http://www.cnblogs.com/chruny/p/5045245.html