题目:
解答:
题目标注为hard,但是其实难度不高,没有什么复杂的算法。
主要是情况区分处理。
- 每读取x个单词,直到 ∑ x = b e g i n x = e n d x . s i z e ≤ m a x W i d t h \sum_{x=begin}^{x=end} x.size \le maxWidth x=begin∑x=endx.size≤maxWidth
- 如果x 取到了最后一个单词,则使用自然布局,每个单词分隔一个空格
- 否则,取空格为平均值 ( m a x W i d t h − s u m s i z e ) / ( w o r d c n t − 1 ) (maxWidth-sumsize) / (wordcnt - 1) (maxWidth−sumsize)/(wordcnt−1)
- 多余空格从左至右分配给每个单词间隙
代码:
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
int len = words.size();
int index = 0;
vector<string> result;
int beginindex = 0, endindex = 0, sumsize;
while(true){
sumsize = 0;
string tmp(maxWidth, ' ');
while(endindex < len){
if(sumsize + words[endindex].size() + endindex - beginindex > maxWidth)
break;
sumsize += words[endindex].size();
++endindex;
}
//到达了末尾
int index = 0;
if(endindex == len){
for(int i = beginindex;i < endindex; ++i){
for(int j = 0;j < words[i].size(); ++j)
tmp[index++] = words[i][j];
if(index < maxWidth)
tmp[index++] = ' ';
}
}else{
//只包含部分,必须区分间隔
int wordcnt = endindex - beginindex;
if(wordcnt == 1){
for(int i = 0;i < sumsize; ++i)
tmp[index++] = words[beginindex][i];
index += maxWidth - sumsize;
}else{
int averagespace = (maxWidth - sumsize) / (wordcnt - 1);
int remainspace = (maxWidth - sumsize) - averagespace * (wordcnt - 1);
for(int i = beginindex;i < endindex - 1; ++i){
for(int j = 0;j < words[i].size(); ++j)
tmp[index++] = words[i][j];
index = index + averagespace;
if(remainspace > 0){
--remainspace;
index++;
}
}
for(int i = 0;i < words[endindex-1].size(); ++i)
tmp[index++] = words[endindex-1][i];
}
}
beginindex = endindex;
result.push_back(tmp);
if(endindex == len) break;
}
return result;
}
};
更新会同步在我的网站更新(https://zergzerg.cn/notes/webnotes/leetcode/index.html)