题目:
解题思路:
主要理清楚题目的规则和思路
慢慢一点点的写
代码:
import java.util.ArrayList;
import java.util.List;
public class LC81 {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> ans = new ArrayList<>();
int currentLen = 0;
int start = 0;
int end = 0;
for (int i = 0; i < words.length;) {
//判断加入该单词是否超过最长长度
//分了两种情况,一种情况是加入第一个单词,不需要多加 1
//已经有单词的话,再加入单词,需要多加个空格,所以多加了 1
if (currentLen == 0 && currentLen + words[i].length() <= maxWidth
|| currentLen > 0 && currentLen + 1 + words[i].length() <= maxWidth) {
end++;
if (currentLen == 0) {
currentLen = currentLen + words[i].length();
} else {
currentLen = currentLen + 1 + words[i].length();
}
i++;
} else {
int sub = maxWidth - currentLen + (end - start) - 1;
if (end - start == 1) {
String blank = getStringBlank(sub);
ans.add(words[start] + blank);
} else {
StringBuilder temp = new StringBuilder();
temp.append(words[start]);
int averageBlank = sub / ((end - start) - 1);
//如果除不尽,计算剩余空格数
int missing = sub - averageBlank * ((end - start) - 1);
String blank = getStringBlank(averageBlank + 1);
int k = 1;
for (int j = 0; j < missing; j++) {
temp.append(blank + words[start+k]);
k++;
}
blank = getStringBlank(averageBlank);
for (; k <(end - start); k++) {
temp.append(blank + words[start+k]);
}
ans.add(temp.toString());
}
start = end;
currentLen = 0;
}
}
StringBuilder temp = new StringBuilder();
temp.append(words[start]);
for (int i = 1; i < (end - start); i++) {
temp.append(" " + words[start+i]);
}
temp.append(getStringBlank(maxWidth - currentLen));
ans.add(temp.toString());
return ans;
}
//得到 n 个空白
private String getStringBlank(int n) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < n; i++) {
str.append(" ");
}
return str.toString();
}
public static void main(String[] args) {
String[] arr = new String[]{"This", "is", "an", "example", "of", "text", "justification."};
LC81 lc = new LC81();
List<String> strings = lc.fullJustify(arr, 16);
for (int i = 0; i < strings.size(); i++) {
System.out.println(strings.get(i));
}
}
}