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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

text 两端对齐 小程序_leetcode 68 文本左右对齐

發布時間:2025/3/11 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 文本左右对齐的全部內容,希望文章能夠幫你解決所遇到的問題。

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