Leetcode 68 Solution
This article provides solution to leetcode question 68 (text-justification)
Access this page by simply typing in "lcs 68" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/text-justification
Solution
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> res;
int l = 0;
int r = 0;
int currWidth = 0;
while (r < words.size())
{
if (l == r)
currWidth += words[r++].size();
else if (currWidth + words[r].size() + 1 <= maxWidth)
currWidth += words[r++].size() + 1;
else
{
string localstr = words[l];
if (r - l > 1)
{
int total_spaces = maxWidth - currWidth + r - l - 1;
int local_spaces = total_spaces / (r - l - 1);
int left_spaces = total_spaces - local_spaces * (r - l - 1);
for (int i = l + 1; i < r; i++)
{
if (left_spaces > 0)
{
localstr += string(local_spaces + 1, ' ') + words[i];
left_spaces--;
}
else
localstr += string(local_spaces, ' ') + words[i];
}
}
else
localstr += string(maxWidth - localstr.size(), ' ');
res.push_back(localstr);
l = r;
currWidth = 0;
}
}
string last_str = words[l];
for (int i = l + 1; i < r; i++)
last_str += " " + words[i];
last_str += string(maxWidth - last_str.size(), ' ');
res.push_back(last_str);
return res;
}
};