-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfullJustify.cpp
More file actions
30 lines (25 loc) · 1006 Bytes
/
fullJustify.cpp
File metadata and controls
30 lines (25 loc) · 1006 Bytes
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
class Solution{
public:
vector<string> fullJustify(vector<string>& words, int maxWidth)
{
vector<string> justifiedText;
for (unsigned i = 0, j, lineWordsLength = 0; i < words.size(); i = j, lineWordsLength = 0)
{
for (j = i; j < words.size() && lineWordsLength + words[j].size() + (j - i) <= maxWidth; lineWordsLength += words[j++].size());
string line = words[i];
for (unsigned k = i + 1; k < j; ++k)
{
int paddingSize = 1;
if (j < words.size())
{
paddingSize = (maxWidth - lineWordsLength) / (j - k) + ((maxWidth - lineWordsLength) % (j - k) != 0 ? 1 : 0);
lineWordsLength += paddingSize;
}
line.append(paddingSize, ' ').append(words[k]);
}
line.append(maxWidth - line.size(), ' ');
justifiedText.push_back(line);
}
return justifiedText;
}
};