forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfullJustify.cpp
More file actions
54 lines (49 loc) · 1.38 KB
/
fullJustify.cpp
File metadata and controls
54 lines (49 loc) · 1.38 KB
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
#define REP(i,n) for(int i=0;i<(n);++i)
class Solution {
public:
string doit(vector<string>& mm, int L, bool last) {
string res = "";
int m = mm.size();
int len = 0;
REP(i,mm.size()) len += mm[i].length();
if (m == 1 || last) {
REP(i,mm.size()) res += mm[i];
REP(i,L-len) res += " ";
return res;
}
int left = L - len;
int avg = left / (m - 1);
int sz = left - avg * (m - 1);
string sps = "";
REP(i,avg) sps += " ";
REP(i,mm.size()) {
if (i > 0) {
res += sps;
if (i <= sz) res += " ";
}
res += mm[i];
}
return res;
}
vector<string> fullJustify(vector<string> &words, int L) {
int n = words.size();
int idx = 0;
vector<string> ret;
while (idx < n) {
vector<string> mm;
int len = words[idx].length();
mm.push_back(words[idx++]);
while (idx < n) {
if (len + 1 + words[idx].length() <= L) {
len += 1 + words[idx].length();
mm.push_back(" " + words[idx++]);
} else {
break;
}
}
bool last = (idx == n);
ret.push_back(doit(mm, L, last));
}
return ret;
}
};