日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

[Leetcode]@python 68. Text Justification

發布時間:2024/4/15 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。