class Solution { public List<String> fullJustify(String[] words, int maxWidth) { List<String> res=new ArrayList<String>(); int idx=0; while(idx<words.length) { int curlen=0; int i=idx; while(i<words.length&&curlen+words[i].length()<=maxWidth) { curlen+=words[i].length()+1; i++; } curlen--; StringBuilder sb=new StringBuilder(); if(i==words.length||i==idx+1) { for(int k=idx;k<i-1;k++) sb.append(words[k]+" "); sb.append(words[i-1]); for(int k=sb.length();k<maxWidth;k++) sb.append(" "); res.add(sb.toString()); } else { int space=(maxWidth-curlen)/(i-idx-1); int extra=(maxWidth-curlen)%(i-idx-1); String sp=""; for(int k=0;k<space;k++) sp+=" "; for(int k=idx;k<i-1;k++) { sb.append(words[k]+" "+sp); if(extra>0) { sb.append(" "); extra--; } } sb.append(words[i-1]); res.add(sb.toString()); } idx=i; } return res; } }