leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0068.cpp (1529B)
0 class Solution {
1 public:
2 vector<string> fullJustify(vector<string> &words, int maxWidth) {
3 vector<string> res;
4 int i = 0, j;
5 while (i < words.size()) {
6 int count = words[i].size(); // character count
7 for (j = i + 1; j < words.size() && count <= maxWidth; j++)
8 count += words[j].size() + 1; // word lenght + at least 1 space
10 if (count > maxWidth) count -= words[--j].size() + 1; // if we overshot, remove last word
11 int wordc = j - i; // number of words for the current row
12 count -= wordc - 1; // remove minimum padding added from the character count;
13 int white = maxWidth - count; // how much whitespace
14 string row = words[i++];
15 if (i != j) {
16 if (j != words.size()) {
17 while (i < j) {
18 int segment = ceil((double)white / (wordc-- - 1));
19 row += string(min(segment, white), ' ') + words[i++];
20 white -= segment;
21 }
22 } else {
23 // last row, adjust left
24 while (i < j)
25 row += " " + words[i++];
26 }
27 }
28 row += string(maxWidth - row.size(), ' '); // padd the remainder of the row
29 res.push_back(row); // push the current row to the result
30 }
31 return res;
32 }
33 };