-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext-justification.cc
59 lines (54 loc) · 2.11 KB
/
text-justification.cc
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
#pragma once
#include "leetcode.h"
using namespace std;
using namespace utils;
class Solution {
public:
vector<string> fullJustify(vector<string> &words, const int max_width) {
vector<string> lines;
string line;
line.reserve(max_width);
for (int pos = 0; pos < words.size();) {
line = words[pos];
int n_intervals = 0, n_chars = words[pos].size(), line_cur = ++pos;
while (pos < words.size()) {
if (n_chars + n_intervals + words[pos].size() >= max_width) break;
n_chars += words[pos++].size();
++n_intervals;
}
if (pos >= words.size()) {
for (int _ = 0; _ < n_intervals; ++_, ++line_cur) {
line += " ";
line += words[line_cur];
}
line.resize(max_width, ' ');
lines.push_back(line);
return lines;
}
if (n_intervals == 0) {
line.resize(max_width, ' ');
} else {
const int count = (max_width - n_chars) / n_intervals;
const int rest = (max_width - n_chars) % n_intervals;
for (int _ = 0; _ < rest; ++_, ++line_cur) {
line += string(count + 1, ' ');
line += words[line_cur];
}
for (int _ = 0; _ < n_intervals - rest; ++_, ++line_cur) {
line += string(count, ' ');
line += words[line_cur];
}
}
lines.push_back(line);
}
return lines;
}
};
int main(int argc, char const *argv[]) {
vector<string> words1{"This", "is", "an", "example", "of", "text", "justification."};
vector<string> words2{"What", "must", "be", "acknowledgment", "shall", "be"};
Solution solution;
for (const auto &it : solution.fullJustify(words1, 16)) { cout << "\"" << it << "\"" << endl; }
cout << endl;
for (const auto &it : solution.fullJustify(words2, 16)) { cout << "\"" << it << "\"" << endl; }
}