给定一个单词数组和一个长度 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 "
]
解析:本题在理解上没有什么难的,也没有用到什么算法上的知识。问题在于要求太多,题目复杂。
class Solution {
public:
int allwidth = 0; //目前单词至少需要的字符数
int wordwidth = 0; //目前单词总字符数
int wordcount = 0; //目前单词数量
vector<string> res; //待返回结果
vector<string> tmp; //储存待处理字符串
bool islast = false; //是否为最后一行
int maxwidth;
vector<string> fullJustify(vector<string>& words, int maxWidth) {
maxwidth=maxWidth;
for(int i=0;i<=words.size();++i){
//已经到达最后一行
if(i==words.size()){
islast=true;
pushstr();
}
else{
//如果还能继续增加单词
if(allwidth + words[i].size() <= maxwidth){
allwidth += words[i].size()+1;
wordwidth += words[i].size();
++wordcount;
tmp.push_back(words[i]);
}
//无法增加,对目前单词进行处理
else{
pushstr();
--i;
}
}
}
return res;
}
//将目前的单词处理为字符串
void pushstr(){
string str;
//最后一行,左对齐,单词中间只有一个空格
if(islast){
for(string &s:tmp){
str+=s;
str+=' ';
}
str.pop_back();
while(str.size()<maxwidth) str+=' ';
res.push_back(str);
}
else{
//如果只有一个单词
if(tmp.size()==1){
str += tmp[0];
for(int i=0;i<maxwidth-wordwidth;++i) str += ' ';
res.push_back(str);
}
//有多个单词
else{
//n个单词有n-1个空位
int n = tmp.size()-1;
//有m个空格
int m = maxwidth-wordwidth;
//每一个空位有几个空格
vector<int> spa(n,0);
for(int i=0;i<n;++i){
spa[i]=m/n;
}
for(int i=0;i<m%n;++i) ++spa[i];
//按序处理
for(int i=0;i<n;++i){
str+=tmp[i];
for(int j=0;j<spa[i];++j) str+=' ';
}
str+=tmp[n];
res.push_back(str);
spa.clear();
}
}
allwidth=0;
wordwidth=0;
wordcount=0;
tmp.clear();
}
};