Skip to content

Commit 9a9c47c

Browse files
committed
3
1 parent 4f65b33 commit 9a9c47c

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
class Solution {
2+
public:
3+
vector<string> fullJustify(vector<string>& words, int L) {
4+
// Start typing your C/C++ solution below
5+
// DO NOT write int main() function
6+
7+
vector<int> needed_lines(words.size(), 0);
8+
int count_line = 1;
9+
int len = 0;
10+
for (int i = 0; i < words.size(); i++) {
11+
if (len + words[i].size() + 1 <= L + 1) {
12+
needed_lines[i] = count_line;
13+
len += words[i].size() + 1;
14+
}
15+
else {
16+
count_line += 1;
17+
len = words[i].size() + 1;
18+
needed_lines[i] = count_line;
19+
}
20+
}
21+
vector<string> justified;
22+
int start = 0;
23+
24+
while (start < words.size()) {
25+
int end = start + 1;
26+
int words_len = words[start].size();
27+
while (end < words.size() && needed_lines[start] == needed_lines[end]) {
28+
words_len += words[end].size();
29+
end += 1;
30+
}
31+
int words_num = end - start;
32+
string justified_line;
33+
if (words_num == 1) {
34+
justified_line += words[start];
35+
justified_line.append(L - words_len, ' ');
36+
}
37+
else {
38+
int extra = (L - words_len) % (words_num - 1);
39+
int blank = (L - words_len) / (words_num - 1);
40+
if (end == words.size()) {
41+
extra = 0; blank = 1;
42+
}
43+
for (int i = start; i < end; i++) {
44+
justified_line += words[i];
45+
if (i == end -1) continue;
46+
if (extra > 0) {
47+
justified_line.append(blank + 1, ' ');
48+
extra -= 1;
49+
}
50+
else
51+
justified_line.append(blank, ' ');
52+
}
53+
if (end == words.size()) {
54+
justified_line.append(L - words_len - words_num + 1, ' ');
55+
}
56+
}
57+
justified.push_back(justified_line);
58+
start = end;
59+
}
60+
return justified;
61+
}
62+
};

0 commit comments

Comments
 (0)