blob: d45bead4e00eb788de1d29b157e22700bc7a7db4 (
plain)
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
#include "leetcode.h"
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int maxWidth) {
vector<string> ans, taken;
int lineLen = 0;
for (auto word : words) {
if (lineLen + word.size() + taken.size() > maxWidth) {
ans.push_back(lineBegin(taken, maxWidth - lineLen));
taken.clear();
taken.push_back(word);
lineLen = word.size();
} else {
taken.push_back(word);
lineLen += word.size();
}
}
ans.push_back(lineEnd(taken, maxWidth - lineLen));
return ans;
}
private:
string lineBegin(vector<string> &v, int toFill) {
string ans = "";
if (v.size() == 1) {
ans += v[0];
while (toFill--)
ans += ' ';
return ans;
}
int space = toFill / (v.size() - 1);
int extras = toFill % (v.size() - 1);
ans += v[0];
for (int i = 1; i < v.size(); i++) {
for (int j = 0; j < space; j++)
ans += ' ';
if (extras) {
extras--;
ans += ' ';
}
}
return ans;
}
string lineEnd(vector<string> &v, int toFill) {
string ans = v[0];
for (int i = 1; i < v.size(); i++) {
toFill--;
ans += ' ';
ans += v[i];
}
while (toFill--)
ans += ' ';
return ans;
}
};
|