-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathText Justification.cpp
68 lines (67 loc) · 1.55 KB
/
Text Justification.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
60
61
62
63
64
65
66
67
68
// Runtime: 0 ms (Top 100.00%) | Memory: 7.5 MB (Top 53.55%)
class Solution {
string preprocessing(string &f, int space, int limit)
{
int noofspace = limit-f.size()+space;
int k = 0;
string r = "";
while(space)
{
int n = noofspace / space;
if((noofspace%space) != 0)
n += 1;
noofspace -= n;
while(f[k] != ' ')
{
r += f[k];
k++;
}
k++;
while(n--)
{
r += ' ';
}
space--;
}
while(k < f.size())
{
r += f[k];
k++;
}
while(noofspace--)
r += ' ';
return r;
}
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> ans;
string f = "";
int space = 0;
for(string &str : words)
{
if((f.size() + str.size() + 1) <= maxWidth && f.size() > 0)
{
f += ' ' + str;
space++;
}
else
{
if(f.size() > 0){
f = preprocessing(f, space, maxWidth);
ans.push_back(f);
f = "";
}
f += str;
space = 0;
}
}
int sz = f.size();
while(sz < maxWidth)
{
f += ' ';
sz++;
}
ans.push_back(f);
return ans;
}
};