LeetCode 68. 文本左右对齐(字符串逻辑题)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 68. 文本左右对齐(字符串逻辑题)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 題目
給定一個單詞數組和一個長度 maxWidth,重新排版單詞,使其成為每行恰好有 maxWidth 個字符,且左右兩端對齊的文本。
你應該使用“貪心算法”來放置給定的單詞;也就是說,盡可能多地往每行中放置單詞。必要時可用空格 ’ ’ 填充,使得每行恰好有 maxWidth 個字符。
要求盡可能均勻分配單詞間的空格數量。如果某一行單詞間的空格不能均勻分配,則左側放置的空格數要多于右側的空格數。
文本的最后一行應為左對齊,且單詞之間不插入額外的空格。
說明:
單詞是指由非空格字符組成的字符序列。
每個單詞的長度大于 0,小于等于 maxWidth。
輸入單詞數組 words 至少包含一個單詞。
來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/text-justification
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
class Solution { // C++ public:vector<string> fullJustify(vector<string>& words, int maxWidth) {vector<string> ans;string line;int i, width = 0, wc;for(i = 0; i < words.size(); ++i){if(line.empty()){ //為空,直接加入單詞line = words[i];width = words[i].size();wc = 1;//單詞個數}else{if(width+1+words[i].size() <= maxWidth){ //還能加入line += " "+words[i];width += 1+words[i].size();wc++;}else//超了,放不下i{process(wc,line,maxWidth,width);//處理單詞ans.push_back(line);//該行存入答案line = "";width = wc = 0;i--;}}}line += string(maxWidth-width,' ');//最后一行左對齊,后面補空格ans.push_back(line);return ans;}void process(int wc, string& line, int maxWidth, int width){if(wc == 1)//只有一個單詞,直接后面補空格{line += string(maxWidth-width,' ');return;}int space = maxWidth - width;//需要的空格數int n = space/(wc-1);//平均插入個數int pos = wc-1;//可以插入的位置個數for(int i = line.size()-1; i >= 0; --i){if(line[i] == ' '){ //找到空格了line.insert(i,n,' ');//插入平均的個數space -= n;//空格數更新pos--;//位置數更新if(pos > 0 && space%pos == 0)//位置還有,且能被整除n = space/pos;//變成整除的(左邊空格大于右邊條件)}}} };0 ms 7 MB
class Solution:# py3def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:ans = []line = ""width = 0wc = 0def process(wc,line,width):if wc==1:line += ' '*(maxWidth-width)return linespace = maxWidth-widthn = space//(wc-1)pos = wc-1line = list(line)size = len(line)for i in range(size-1,-1,-1):if line[i]==' ':line.insert(i, ' '*n)space -= npos -= 1if pos > 0 and space%pos==0:n = space//posline = "".join(line)return linei = 0while i < len(words):if len(line)==0:line = words[i]width = len(words[i])wc = 1else:if width+1+len(words[i]) <= maxWidth:line += " "+words[i]width += 1+len(words[i])wc += 1else:temp = process(wc,line,width)ans.append(temp)line = ""width, wc = 0, 0i -= 1i += 1line += ' '*(maxWidth-width)ans.append(line)return ans44 ms 13.5 MB
總結
以上是生活随笔為你收集整理的LeetCode 68. 文本左右对齐(字符串逻辑题)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 604. 迭代压缩字符
- 下一篇: LeetCode 302. 包含全部黑色