# 程序分享--常见算法/编程面试题：文本左右对齐

87 篇文章 1 订阅

-------------------------------------正文----------------------------------------

• 单词是指由非空格字符组成的字符序列。
• 每个单词的长度大于 0，小于等于 maxWidth
• 输入单词数组 words 至少包含一个单词。

输入: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16

[
"This    is    an",
"example  of text",
"justification.  "
]


输入:words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16

[
"What   must   be",
"acknowledgment  ",
"shall be        "
]

因为最后一行应为左对齐，而不是左右两端对齐。
第二行同样为左对齐，这是因为这行只包含一个单词。


输入: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                  "
]


• 1 <= words.length <= 300
• 1 <= words[i].length <= 20
• words[i] 由小写英文字母和符号组成
• 1 <= maxWidth <= 100
• words[i].length <= maxWidth

-------------------------------------答案----------------------------------------

class Solution {
public:
struct Line {
int st;
int ed;
int lw;
};
string space_factory(int n) {
return string(n,' ');
}

vector<string> fullJustify(vector<string>& words, int maxWidth) {
int len = words.size();
int wordsize[len];
for(int i = 0;i < len;i++) {
wordsize[i] = words[i].size();
}

vector<Line> lines;
int start = 0, count = 0, sum = 0;
while(start < len) {
count = 0;
sum = 0;
while(start+count < len) {
if(sum+count+wordsize[start+count]>maxWidth) {
lines.push_back({start,start+count-1,sum});
break;
}
sum += wordsize[start+count];
count++;
}
start += count;
}
start -= count;

vector<string> res;
for(int i = 0;i < lines.size();i++) {
auto line = lines[i];
int sum_spaces = maxWidth-line.lw;
string new_line = "";

new_line += words[line.st];
if(line.st == line.ed) {
new_line += space_factory(sum_spaces);
} else {
int sigle_spaces = (sum_spaces)/(line.ed-line.st);
int remain_spaces = (sum_spaces)%(line.ed-line.st);
for(int j = 1;line.st+j<=line.ed;j++) {
if(j-1 < remain_spaces) {
new_line += space_factory(sigle_spaces+1);
} else {
new_line += space_factory(sigle_spaces);
}
new_line += words[line.st+j];
}
}
res.push_back(new_line);
}

string new_line = "";
new_line += words[start];
sum = wordsize[start];
for(int i = start+1;i < len;i++) {
new_line += " ";
new_line += words[i];
sum +=  wordsize[i];
}
new_line += space_factory(maxWidth-sum-(len-start-1));
res.push_back(new_line);

return res;
}
};


C#实例：SQL如何添加数据》，《C#实战分享--爬虫的基础原理及实现》欢迎大家阅读。

• 39
点赞
• 15
收藏
觉得还不错? 一键收藏
• 打赏
• 0
评论
11-28 1306
07-06 2万+
05-20 589
02-16 1392
09-22 2万+
04-07 1907
10-18 551
07-14 443
07-14 212
07-15 770

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥1 ¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。