class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth)
{
std::vector<std::string> result;
int line_index = 0;
int letter_count = 0;
int i = 0;
std::vector<int> dist;
while(i < words.size())
{
letter_count += words[i].length();
if(i+1 >= words.size())
{
dist.push_back(i);
break;
}
else
{
if(letter_count == maxWidth || letter_count + words[i+1].length() + 1 > maxWidth)
{
line_index++;
letter_count = 0;
dist.push_back(i);
i++;
continue;
}
else
{
letter_count++;
i++;
}
}
}
std::string space = " ";
int start = 0;
for(int i = 0; i <= line_index; i++)
{
std::string l;
int end = dist[i]; //first line use end+1 words and has end slots
int len = 0;
int up, down;
int slot = end - start ;
if(slot ==0 ) slot =1;
for(int i = start; i <=end; i++)
{
len += words[i].length();
}
int spaces_left = maxWidth - len;
if(end == start)
{
up = spaces_left;
down = spaces_left;
}
else
{
up = ceil(float(spaces_left) / (end - start));
down = floor(float(spaces_left) / (end - start));
}
int x = 0;
while (spaces_left % slot )
{
x += 1;
spaces_left--;
}
int up_num = x;
int down_num = slot-up_num;
if(end != words.size() -1)
{
for(int a = start;a < up_num + start; a++)
{
l += words[a];
for(int c =0; c < up; c++)
{
l += space;
}
}
for(int a = start + up_num; a<end; a++)
{
l += words[a];
for(int c =0; c < down;c++)
{
l += space;
}
}
l += words[end];
while(l.length() < maxWidth)
{
l += space;
}
result.push_back(l);
start = end + 1;
}
else
{
if(end == start)
{
l+= words[start];
for(int c = 0; c < maxWidth -words[start].length(); c++)
{
l += space;
}
result.push_back(l);
}
else
{
while(end >= start)
{
l += words[start];
if(l.length() < maxWidth)
{l += space;}
start++;
}
while(l.length() <maxWidth)
{
l += space;
}
result.push_back(l);
}
}
}
return result;
}
};