-
Notifications
You must be signed in to change notification settings - Fork 3
/
68.cpp
59 lines (57 loc) · 2.03 KB
/
68.cpp
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
57
58
59
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
int wordIdx = 0;
int n = words.size();
vector<string> res;
while (wordIdx < n) {
int start = wordIdx;
int length = words[wordIdx].size() + 1;
int lengthWord = words[wordIdx].size();
while (wordIdx + 1 < n && length + words[wordIdx + 1].size() <= maxWidth) {
wordIdx++;
length += words[wordIdx].size();
length += 1;
lengthWord += words[wordIdx].size();
}
if (wordIdx == n - 1) {
string temp = "";
for (int i = start; i <= wordIdx; ++i) {
temp += words[i];
temp.push_back(' ');
}
if (temp.size() > maxWidth) temp.pop_back();
else {
int empty = maxWidth - temp.size();
while (empty--) temp.push_back(' ');
}
res.push_back(temp);
}
else if (start == wordIdx) {
string temp = words[wordIdx];
int empty = maxWidth - words[wordIdx].size();
while (empty--) temp.push_back(' ');
res.push_back(temp);
}
else {
int chunks = wordIdx - start;
int empty = (maxWidth - lengthWord) / chunks;
int remain = (maxWidth - lengthWord) % chunks;
string temp = "";
string emptyStr(empty, ' ');
for (int i = start; i <= wordIdx; ++i) {
temp += words[i];
if (i == wordIdx) break;
temp += emptyStr;
if (remain) {
remain--;
temp.push_back(' ');
}
}
res.push_back(temp);
}
wordIdx++;
}
return res;
}
};