private String getWordLine(String[] words, int maxWidth, int begin, int end) { StringBuilderline=newStringBuilder();
// the last line, or the line has only one word if (end == words.length || end == begin + 1) { line.append(words[begin]); for (inti= begin + 1; i < end; i++) { line.append(" ").append(words[i]); }
appendSpace(line, maxWidth - line.length()); } else { intwordWidth=0; for (inti= begin; i < end; i++) { wordWidth += words[i].length(); }
inttotalSpace= maxWidth - wordWidth; intwordSpace= totalSpace / (end - begin - 1); intremainSpace= totalSpace % (end - begin - 1);
for (inti= begin; i < end - 1; i++) { line.append(words[i]); appendSpace(line, wordSpace); if (remainSpace > 0) { line.append(" "); remainSpace--; } }