/*本题是一道模拟题,直接按照如下规则进行求解即可:
1.每行中的单词之间都有空隙,每个空隙的字符数尽量相等(不能做到相等的,
从左边开始增加空隙的空格数)。
2.最后一行的空格全部放在右边。
方法参考自:https://github.com/soulmachine/leetcode*/
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) {
vector<string> res;
int begin(0), len(0);//从word开始的下标,当前长度
for(int i = 0; i < words.size(); ++i){
if(len + words[i].size() + i - begin > L){
//再加入当前单词后,该行已经大于L,所以在words[e,i)应组成一行
res.push_back(connect(words, begin, i, len, L, false));
//从第i个单词重新计数
begin = i;
len = 0;
}
//将第i个单词计入该行的长度
len += words[i].size();
}
//将最后一行加入
res.push_back(connect(words, begin, words.size(), len, L, true));
return res;
}
string connect(vector<string> &words, int begin, int end, int len, int L, bool isLast){
//本函数的功能是将words[begin,end)部分链接成行
string line;
for(int i = begin; i < end; ++i){
line += words[i];
//加入空隙
if(i == end-1) continue;//最右边的单词后面,无需加入空隙
if(isLast){//最后一行的单词之间只加入一个空格
line += " ";
}
else{
int num((L-len)/(end - begin - 1));//平均给个空隙的空格数
if(i - begin < (L-len)%(end - begin - 1)) ++num;//多余的空格加入左边的空隙
line.append(num, ' ');
}
}
if(line.size() < L){//最后一行,在右边加入剩余的空格
line.append(L - line.size(), ' ');
}
return line;
}
};
06-24
07-18
07-18
07-18
07-18
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交