### 題目
給定一個單詞數組和一個長度 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 "
]
### 思路
這個題目沒意思是真的麻煩,要考慮每個情況,把情況都考慮清楚就基本沒什麼難度了,第一步先確定每一行最多能放多少個單詞,第二步確定每行可以放的單詞數目是不是隻有一個或者是最後一行(兩者的處理方法是一樣的),第三步再根據兩種情況分別處理。
### code
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string>res;
int i=0;
while(i<words.size()){
int residue_wid=0;
int begin=i;
while(i<words.size() && residue_wid+words[i].size()<=maxWidth){//每一行添加最多的單詞。
residue_wid+=words[i].size()+1;
++i;
}
if(i==words.size()){//判斷是否是最後一行。
res.push_back(packagestring(words,begin,i-1,residue_wid-1,maxWidth,false));
break;
}
res.push_back(packagestring(words,begin,i-1,residue_wid-1,maxWidth,true));
}
return res;
}
string packagestring(vector<string>& words, int starter, int ender, int strlen,int maxWidth,bool tail){
string res="";
if(tail && starter<ender){
int cnt=ender-starter;//代表有幾個空格位(空格個數等於字符串數-1)
int blk=(maxWidth-strlen)/cnt+1;//每個位置最少放幾個空格
string spc=string(blk,' ');//n個空格
int ofst=(maxWidth-strlen)%cnt;//剩下的空格。
for(int i=starter;i<ender;++i)//左邊要比右邊多,但是不需要是絕對大於,直接從左往右都分配一個。
{
res+=words[i]+spc;//加上最少空格
if(i-starter<ofst)res+=' ';//還有剩下的空格就加上。
}
res+=words[ender];
}
else//只有一個字符串或者最後字符串,方法是一樣的,都是左對齊。
{
string spc=string(maxWidth-strlen,' ');//每個空格位只放一個空格,剩下的全部添加到後面。
for(int i=starter;i<ender;++i){
res+=words[i]+' ';
}
res+=words[ender]+spc;//直接添加到最後。
}
return res;
}
};