public class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> res = new LinkedList<String>();
if( words == null || words.length < 1) return res;
int maxWidthCopy = maxWidth;
int i = 0;
while(i < words.length){
List<String> wordList = new ArrayList<String>();
maxWidthCopy = maxWidth;
int count = 0;
while(words[i].length() <= maxWidthCopy){
wordList.add(words[i]);
maxWidthCopy -= words[i].length() + 1;
i++;
count++;
if(i >= words.length){
break;
}
}
if(i < words.length){
res.add(eachLine(wordList, maxWidthCopy + count));
} else { // For the last line of text
String temp = "";
int extraSpace = maxWidthCopy + count;
for(int j = 0; j < wordList.size(); j++){
if(j > 0) {
temp += " ";
extraSpace--;
}
temp += wordList.get(j);
}
if(extraSpace > 0 ){
temp += new String(new char[extraSpace]).replace("\0", " ");
}
res.add(temp);
}
}
return res;
}
public String eachLine(List<String> words, int numOfExtraSpace){
String res = "";
int count = words.size();
if(words == null || count < 1) return res;
if( numOfExtraSpace == 0){
for(int i = 0; i < count; i++){
if(i > 0){
res += " ";
}
res += words.get(i);
}
} else if(count == 1){
res += words.get(0);
//res += " " * numOfExtraSpace;
res += new String(new char[numOfExtraSpace]).replace("\0", " ");
} else {
for(int i = 0; i < count; i++){
if(i > 0){
if(i <= numOfExtraSpace % (count - 1)){
//res += " " * numOfExtraSpace / (count - 1) + 1;
int num = numOfExtraSpace / (count - 1) + 1;
res += new String(new char[num]).replace("\0", " ");
} else {
//res += " " * numOfExtraSpace / (count - 1);
int num = numOfExtraSpace / (count - 1) ;
res += new String(new char[num]).replace("\0", " ");
}
}
res += words.get(i);
}
}
return res;
}
}
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> res = new ArrayList<>();
List<String> buf = new ArrayList<>();
int len = 0;
for (String word: words) {
if (buf.size() + len + word.length() > maxWidth) {
res.add(justify(buf, len, maxWidth));
buf = new ArrayList<>();
len = 0;
}
buf.add(word);
len += word.length();
}
if (buf.size() > 0) {
StringBuilder last = new StringBuilder(String.join(" ", buf));
while (last.length() < maxWidth) {
last.append(' ');
}
res.add(last.toString());
}
return res;
}
private String justify(List<String> buf, int len, int maxWidth) {
StringBuilder sb = new StringBuilder(buf.get(0));
if (buf.size() == 1) {
while (sb.length() < maxWidth) {
sb.append(' ');
}
} else {
int space = maxWidth - len;
int normal = space / (buf.size() - 1);
int extra = space % (buf.size() - 1);
for (int i = 1; i < buf.size(); i ++) {
for (int j = 0; j < normal + (extra >= i ? 1 : 0); j ++) {
sb.append(' ');
}
sb.append(buf.get(i));
}
}
return sb.toString();
}
}