-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path68-Text-Justification.cpp
More file actions
55 lines (48 loc) · 1.32 KB
/
68-Text-Justification.cpp
File metadata and controls
55 lines (48 loc) · 1.32 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
55
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth)
{
vector<string>v;
int spaces = 0, totChars = 0, l = 0, r = 0;
while( r < words.size() )
{
if( totChars + spaces + words[r].size() > maxWidth )
{
int avail = maxWidth - totChars;
if( spaces > 1 )
spaces -= 1;
int space = avail / spaces;
avail %= spaces;
string s;
for( int i = l; i < r; i++ )
{
s += words[i];
int cnt = 0;
while( cnt++ < space && spaces )
s += ' ';
spaces--;
if( avail > 0 )
avail--, s += ' ';
}
v.push_back(s);
spaces = 0;
totChars = 0;
l = r;
}
spaces++;
totChars += words[r].size();
r++;
}
string s;
for( int i = l; i < r; i++ )
{
s += words[i];
if( i + 1 != r )
s += ' ';
}
while( s.size() < maxWidth )
s += ' ';
v.push_back(s);
return v;
}
};