leetcode 68 文本左右对齐/ textJustification
程序员文章站
2022-05-12 10:05:57
...
题目描述:
比较繁琐的模拟题,写了三四个小时,无参考硬干出来了,一开始还比较高兴,结果查看别人的示范样例发现20行就搞出来了。。思路大体上都差不多:一行一行的处理,第一步确认每一行能装多少个元素,确认完之后再根据不同情况分配空格,对最后一行要特殊处理。代码如下:
示范代码:
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int L) {
vector<string> res;
for(int i = 0, k, l; i < words.size(); i += k) {
for(k = l = 0; i + k < words.size() && l + words[i+k].size() <= L - k; k++) {//L-k因为每一个单词都有一个空格,l是一行中字符的长度
l += words[i+k].size();
}
string tmp = words[i];
for(int j = 0; j < k - 1; j++) {
if(i + k >= words.size()) tmp += " ";//最后一行,只加一个空格
else tmp += string((L - l) / (k - 1) + (j < (L - l) % (k - 1)), ' ');//不是最后一行,补齐空格,最左边(L - l) % (k - 1)个单词后要比之后的多一个空格
tmp += words[i+j+1];
}
tmp += string(L - tmp.size(), ' ');//最后一行,末尾补空格
res.push_back(tmp);
}
return res;
}
};
我的。。。:
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
int i = 0 ;
vector<string> res;
int wordsCnt,prev,blankCnt,blankPlaceLeft,blankPlace,temp,blankgap,total,p,j,tempLeft;
prev = 0;
while(i < words.size()){
temp = 0;
string out;
while(i < words.size()){
if(temp != 0 && words[i].size() + temp + 1 > maxWidth){
break;
}
if(temp == 0 && temp + words[i].size() <= maxWidth){
temp += words[i].size();
i++;
}
if(temp != 0 && temp + 1 + words[i].size() <= maxWidth){
temp += 1;
temp += words[i].size();
i++;
}
}
i = i - 1;//当前行最大数量
total = i - prev + 1;
wordsCnt = 0;
for(j = prev; j <= i; j++) wordsCnt += word[j].size();
if(i == words.size() - 1){//最后一行
if(total == 1){
//res[t] += words[i];
out += words[i];
out.append(maxWidth - wordsCnt,' ');
res.push_back(out);
return res;
}
else{
for(p = prev ;p <= i - 1;p++){
out += words[p];
out.append(1,' ');
}
out += words[p];
out.append(maxWidth - wordsCnt - total + 1,' ');
}
res.push_back(out);
return res;
}
blankCnt = maxWidth - wordsCnt;//空格占有的位置数//3
blankPlace = total - 1;//2
if(blankPlace >= 2) blankPlaceLeft = blankCnt % blankPlace;//1
if(blankPlace >= 2) blankgap = blankCnt / blankPlace;//1
if(total == 1){
//res[t] += words[i];
out += words[i];
//res[t] += //blankCnt 个空格
out.append(blankCnt,' ');
res.push_back(out);
}
else if(total == 2){
//res[t] += words[prev];
out += words[prev];
//res[t] += //blankCnt 个空格
out.append(blankCnt,' ');
//res[t] += words[i];
out += words[i];
res.push_back(out);
}
else{// 单行 字符个数 大于等于3时
if(blankPlaceLeft == 0){
for(p = prev ;p <= i - 1;p++){
out += words[p];
out.append(blankgap,' ');
}
}
else{ //b
tempLeft = 0;
for(p = prev ;p <= i - 1;p++){
out += words[p];
if(tempLeft < blankPlaceLeft){
out.append(1 + blankgap,' ');
tempLeft ++;
}
else{
out.append(blankgap,' ');
}
}
}
out += words[p];
res.push_back(out);
}
prev = i + 1;
i++;
}
}
};
不知不觉就写了那么大一堆,感觉自己还是 too young,还要多学习一个
上一篇: 卧薪尝胆的故事中其实有两个奋斗者!除了勾践还有谁?
下一篇: 顺治登上皇位后,为什么会出家当和尚?