publicclassSolution {publicList<String> fullJustify(String[] words,int maxWidth) {List<String> list =newArrayList<String>();int N =words.length;int right =0;for(int left =0; left < N; left = right){// Each word comes with one space;// Except the first word, so start with -1.int len =-1;for(right = left; right < N && len + words[right].length() +1<= maxWidth; right ++){ len += words[right].length() +1; }// Those are in case there's only one word picked, or in last lineint space =1;int extra =0;if(right != left +1&& right != N){// right - left - 1 is number of gaps space = (maxWidth - len) / (right - left -1) +1; extra = (maxWidth - len) % (right - left -1); }StringBuilder sb =newStringBuilder(words[left]);for(int i = left +1; i < right; i++){for(int j =0; j < space; j++) sb.append(' ');if(extra-->0) sb.append(' ');sb.append(words[i]); }int rightSpace = maxWidth -sb.length();while(rightSpace-->0) sb.append(' ');list.add(sb.toString()); }return list; }}