文本左右对齐

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> res;
for (int i = 0; i < words.size(); i++) {
int j = i + 1;
int len = words[i].size();
// 数一数可以把后面多少个单词加到当前行
while (j < words.size() && len + 1 + words[j].size() <= maxWidth)
len += 1 + words[j++].size();

string line;
if (j == words.size() || j == i + 1) {
// 如果是最后一行
line += words[i];
for (int k = i + 1; k < j; k++) {
line += ' ' + words[k];
}
while (line.size() < maxWidth) line += ' ';
} else {
// cnt 是空隙的数量,j 指向最后一个加入当前行单词的下一个单词,i 指向当前枚举的单词
int cnt = j - i - 1, r = maxWidth - len + cnt;
line += words[i];
int k = 0;
while (k < r % cnt)
line += string(r / cnt + 1, ' ') + words[i + k + 1], k++;
while (k < cnt) line += string(r / cnt, ' ') + words[i + k + 1], k++;
}
res.push_back(line);
i = j - 1;
}
return res;
}
};