题目链接: 点这里
算法: 贪心
尽量容纳下一个单词, 如果不行就下一行处理, 这题麻烦在格式的处理, 具体思路并不难
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> result;
int word_num = 0;
int word_len = 0;
for (int i = 0; i < words.size(); i++) {
// 判断当前单词是否能进入放入当前行
int n = word_len + word_num * 1 + words[i].size();
if (n < maxWidth) { // 当前行能放下这个单词
word_num++;
word_len += words[i].size();
} else if (n == maxWidth) { // 刚好能放下
string str;
for (int j = i - word_num; j < i; j++) {
str += words[j];
str += ' ';
}
str += words[i];
result.push_back(str);
word_num = 0;
word_len = 0;
} else { // 放不下
// 把之前的处理掉, 也就是i - word_num 到 i - 1
result.push_back(generate_str(words, i - word_num, i - 1, word_len, maxWidth));
word_num = 0;
word_len = 0;
i--;
}
}
// 判断word_num是否为零, 如果不为零, 那么生成最后一行
if (word_num != 0) {
string str;
for (int i = words.size() - word_num ; i < words.size(); i++) {
str += words[i];
str += ' ';
}
while (str.length() < maxWidth) {
str += ' ';
}
result.push_back(str);
}
return result;
}
string generate_str(vector<string> &words, int left, int right, int word_len, int max_width) {
// 求出剩余空格的数量
int space_num = max_width - word_len;
// 如果只有一个单词, 那么不全空格返回
if (right == left) {
string str = words[left];
for (int i = space_num; i; i--) {
str += ' ';
}
return str;
}
// 这里算出每个位置的空格数量
int ave = space_num / (right - left);
// 这里算出剩余的空格数量
int surplus = space_num % (right - left);
string spaces, str;
for (int i = 0; i < ave; i++) {
spaces += ' ';
}
for (int i = left; i < right; i++) {
str += words[i];
str += spaces;
// 如果有剩余的空格, 那么就补一个到这个位置
if (surplus != 0) surplus--, str += ' ';
}
str += words[right];
return str;
}
};