[Leetcode]@python 68. Text Justification
題目鏈接
https://leetcode.com/problems/text-justification/
題目原文
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is inserted between words.
For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.
Return the formatted lines as:
["This is an","example of text","justification. " ]題目大意
輸入一個字符串數組和一個規定長度maxWidth。將這個字符串數組的元素盡可能放到長度的L的字符串中,數組中的字符串不能拆開,一個長度L的字符串包括的若干個字符串之間用相等的空格間隔開;如果空格數不能平均分配,則規定左邊的空格數可以大于右邊的空格數
解題思路
直接模擬解決即可,但需要注意細節的處理,例如從開始加入元素,長度增加,然后空格+1后繼續加入新元素,直到長度大于maxWidth
代碼
class Solution(object):def fullJustify(self, words, maxWidth):""":type words: List[str]:type maxWidth: int:rtype: List[str]"""ans = []i = 0while i < len(words):size = 0begin = iwhile i < len(words):if size == 0:newsize = len(words[i])else:newsize = size + len(words[i]) + 1if newsize <= maxWidth:size = newsizeelse:breaki += 1spaceCnt = maxWidth - sizeif i - begin - 1 > 0 and i < len(words):everyCount = spaceCnt // (i - begin - 1)spaceCnt %= i - begin - 1else:everyCount = 0j = begin;s=""while j < i:if j == begin:s = words[j]else:s += ' ' * (everyCount + 1)if spaceCnt > 0 and i < len(words):s += ' 'spaceCnt -= 1s += words[j]j += 1s += ' ' * spaceCntans.append(s)return ans轉載于:https://www.cnblogs.com/slurm/p/5124905.html
總結
以上是生活随笔為你收集整理的[Leetcode]@python 68. Text Justification的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用request简单爬虫
- 下一篇: websocket python爬虫_p