public class TextJustification
{
public TextJustification(){}
public List<String> fullJustify(String[] words, int maxWidth)
{
int length= words.length;
int i=0;
List<String> result= new ArrayList<>();
while(i < length)
{
if(i == length) {break;}
int start= i;
int temp_length= 0;
String temp_str= "";
while(i<length && temp_length+words[i].length() < maxWidth)
{
temp_length += words[i].length();
temp_length++;i++;
}
if(i<length && temp_length+words[i].length() == maxWidth)
{i++;}
int end= i-1;
int space_num= end - start;
if(space_num == 0)
{
temp_str += words[end];
for(int j=0;j<maxWidth-words[end].length();j++)
{temp_str += " ";}
result.add(temp_str);
}
else if(space_num == 1)
{
temp_str += words[start];
for(int j=0;j<maxWidth-
words[start].length()-words[end].length();j++)
{temp_str += " ";}
temp_str += words[end];
result.add(temp_str);
}
else
{
int strs_length= 0;
int word_num= end-start+1;
for(int j=start;j<=end;j++)
{strs_length += words[j].length();}
int space= (maxWidth-strs_length) / space_num;
int index= (maxWidth-strs_length) - space*space_num;
while(index!=0 && word_num!=0)
{
temp_str += words[start];
if(word_num!=1)
{
for(int j=0;j<space+1;j++)
{temp_str += " ";}
}
word_num--;index--;
start++;
}
while(word_num!=0)
{
temp_str += words[start];
if(word_num!=1)
{
for(int j=0;j<space;j++)
{temp_str += " ";}
}
word_num--;index--;
start++;
}
result.add(temp_str);
}
}
String temp_str= result.get(result.size()-1);
int index= 0;
String str= "";
while(index<temp_str.length())
{
if(temp_str.charAt(index) != ' ')
{str += temp_str.charAt(index);index++;}
else
{
str += ' ';index++;
while(index < temp_str.length() && temp_str.charAt(index) == ' ')
{index++;}
}
}
while(str.length()<maxWidth)
{str += ' ';}
result.remove(result.size()-1);
result.add(str);
return result;
}
}