Text Justification
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left justified and no extra space is inserted between words. Note: Each word is guaranteed not to exceed L in length.
难度:hard
这个问题关键是注意一些细节。
public class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> res = new ArrayList<>();
justify(words, 0, maxWidth, res);
return res;
}
private void justify(String[] words, int start, int maxWidth, List<String> res) {
while(start != words.length) {
List<String> tempRes = new ArrayList<>();
int curWidth = 0;
while(start != words.length && curWidth <= maxWidth) {
if(tempRes.isEmpty()) {
tempRes.add(words[start]);
curWidth += words[start].length();
} else {
if(words[start].length() + 1 + curWidth <= maxWidth) {
tempRes.add(" " + words[start]);
curWidth += (words[start].length() + 1);
} else {
break;
}
}
++start;
}
buildLine(tempRes, curWidth, maxWidth, res, start == words.length);
}
}
private void buildLine(List<String> tempRes, int curWidth, int maxWidth, List<String> res, boolean lastLine) {
StringBuilder str = new StringBuilder();
if(tempRes.size() == 1 || lastLine) {
for(String s : tempRes) {
str.append(s);
}
for(int i = curWidth; i < maxWidth; ++i) {
str.append(" ");
}
} else {
while(curWidth < maxWidth) {
for(int i = 0; i < tempRes.size() - 1 && curWidth < maxWidth; ++i, ++curWidth) {
tempRes.set(i, tempRes.get(i) + " ");
}
}
for(String s : tempRes) {
str.append(s);
}
}
res.add(str.toString());
}
}