-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathsol.cpp
60 lines (53 loc) · 1.49 KB
/
sol.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
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution
{
public:
vector<string> fullJustify(vector<string> &words, int maxWidth)
{
vector<string> result;
int i = 0;
while (i < words.size())
{
int wordCount = 0, lineLen = 0;
while (i + wordCount < words.size() &&
lineLen + words[i + wordCount].length() + wordCount <= maxWidth)
{
lineLen += words[i + wordCount].length();
wordCount++;
}
string line;
if (wordCount == 1 || i + wordCount == words.size())
{
for (int j = 0; j < wordCount; j++)
{
line += words[i + j] + " ";
}
line += string(maxWidth - line.length(), ' ');
}
else
{
int spaces = (maxWidth - lineLen) / (wordCount - 1);
int extra = (maxWidth - lineLen) % (wordCount - 1);
for (int j = 0; j < wordCount; j++)
{
line += words[i + j];
if (j != wordCount - 1)
{
line += string(spaces + (extra-- > 0 ? 1 : 0), ' ');
}
}
}
result.push_back(line);
i += wordCount;
}
return result;
}
};
int main()
{
// call the fn here
return 0;
}