text 两端对齐 小程序_leetcode 68 文本左右对齐
生活随笔
收集整理的這篇文章主要介紹了
text 两端对齐 小程序_leetcode 68 文本左右对齐
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個單詞數組和一個長度 maxWidth,重新排版單詞,使其成為每行恰好有 maxWidth 個字符,且左右兩端對齊的文本。
你應該使用“貪心算法”來放置給定的單詞;也就是說,盡可能多地往每行中放置單詞。必要時可用空格 ' ' 填充,使得每行恰好有 maxWidth 個字符。
要求盡可能均勻分配單詞間的空格數量。如果某一行單詞間的空格不能均勻分配,則左側放置的空格數要多于右側的空格數。
文本的最后一行應為左對齊,且單詞之間不插入額外的空格。
說明:
- 單詞是指由非空格字符組成的字符序列。
- 每個單詞的長度大于 0,小于等于 maxWidth。
- 輸入單詞數組 words 至少包含一個單詞。
示例:
輸入: words = ["This", "is", "an", "example", "of", "text", "justification."] maxWidth = 16 輸出: ["This is an","example of text","justification. " ]示例 2:
輸入: words = ["What","must","be","acknowledgment","shall","be"] maxWidth = 16 輸出: ["What must be","acknowledgment ","shall be " ] 解釋: 注意最后一行的格式應為 "shall be " 而不是 "shall be",因為最后一行應為左對齊,而不是左右兩端對齊。 第二行同樣為左對齊,這是因為這行只包含一個單詞。示例 3:
輸入: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"] maxWidth = 20 輸出: ["Science is what we","understand well","enough to explain to","a computer. Art is","everything else we","do " ]# # @lc app=leetcode.cn id=68 lang=python3 # # [68] 文本左右對齊 ## @lc code=start class Solution:def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:n = len(words)start, end = 0, n-1row = 0ans = [[' ' for _ in range(maxWidth)] for _ in range(n)]while(start<n):total = 0num = 0pos = startwhile(pos<n):flag=Falseif total + len(words[pos]) + num>maxWidth:flag=Truebreaktotal+=len(words[pos])num+=1pos+=1if flag:total=maxWidth-totalspace,r=divmod(total,max(1,num-1))pp=0for i in range(start,start+num):ans[row][pp:pp+len(words[i])] = words[i]pp=pp+len(words[i])+spaceif r>0:pp+=1r-=1else:pp=0for i in range(start,start+num):ans[row][pp:pp+len(words[i])] = words[i]pp=pp+len(words[i])+1breakstart = posrow+=1tmp = []for i in range(row+1):tmp.append(''.join(ans[i]))return tmp# @lc code=end總結
以上是生活随笔為你收集整理的text 两端对齐 小程序_leetcode 68 文本左右对齐的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: syslog打印不带等级_linux下s
- 下一篇: mysql以user1登录_在mysql