題目地址:Text Justification
題目簡介:
給定一個單詞數組和一個長度 maxWidth,重新排版單詞,使其成爲每行恰好有 maxWidth 個字符,且左右兩端對齊的文本。
需要儘可能多地往每行中放置單詞,必要時可用空格 ' ' 填充,使得每行恰好有 maxWidth 個字符。
儘可能均勻分配單詞間的空格數量,如果某一行單詞間的空格不能均勻分配,則左側放置的空格數要多於右側的空格數。
文本的最後一行應爲左對齊,且單詞之間不插入額外的空格。說明:單詞是指由非空格字符組成的字符序列。每個單詞的長度大於 0,小於等於 maxWidth。
輸入單詞數組 words 至少包含一個單詞。
示例:
Example 1:
Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
"This is an",
"example of text",
"justification. "
]
Example 2:
Input:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
Output:
[
"What must be",
"acknowledgment ",
"shall be "
]
解釋: 注意最後一行的格式應爲 "shall be " 而不是 "shall be",因爲最後一行應爲左對齊,而不是左右兩端對齊。第二行同樣爲左對齊,這是因爲這行只包含一個單詞。
Example 3:
Input:
words = ["Science","is","what","we","understand","well","enough","to","explain",
"to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20
Output:
[
"Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do "
]
題目解析:
參看地址:[LeetCode] Text Justification 文本左右對齊
C++版:
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int maxWidth) {
vector<string> res;
for (int i = 0; i < words.size();)
{
int j = i, len = 0;
while (j < words.size() && len + words[j].size() + j - i <= maxWidth)
{
len += words[j++].size();
}
string out;
int space = maxWidth - len;
for (int k = i; k < j; ++k)
{
out += words[k];
if (space > 0)
{
int tmp;
if (j == words.size())
{
if (j - k == 1)
tmp = space;
else
tmp = 1;
}
else
{
if (j - k - 1 > 0)
{
if (space % (j - k - 1) == 0)
tmp = space / (j - k - 1);
else
tmp = space / (j - k - 1) + 1;
}
else
tmp = space;
}
out.append(tmp, ' ');
space -= tmp;
}
}
res.push_back(out);
i = j;
}
return res;
}
};