这道题果然不容易写对啊。首先为了写对,我写完以后对着代码又检查了一阵,挺好,而且发现自己偶尔写点注释也便于自己理解。
然后居然超时了,主要原因就是计算长度为n的空字符串花时间太多,就用了个数组一开始先算好存起来。这里用new String[L+1]主要为了避免L为0的情况。
public class Solution { public ArrayList<String> fullJustify(String[] words, int L) { // Start typing your Java solution below // DO NOT write main() function ArrayList<String> result = new ArrayList<String>(); String[] spaces = new String[L+1]; StringBuilder builder = new StringBuilder(); for (int i = 0; i < L+1; i++) { spaces[i] = builder.toString(); builder.append(' '); } int len = words.length; int i = 0; while (i < len) { int j = i; int total = words[i].length(); while (true) { j++; if (j == len) break; int w = words[j].length(); if (total + w + 1 > L) break; total += w + 1; } int left = L - total; int c = j - i; if (c == 1) { // single word StringBuilder sb = new StringBuilder(words[i]); sb.append(spaces[left]); result.add(sb.toString()); } else { // multi-word if (j == len) { // last line StringBuilder sb = new StringBuilder(words[i]); for (int x = i+1; x < j; x++) { sb.append(' '); sb.append(words[x]); } sb.append(spaces[left]); result.add(sb.toString()); } else { int k = left / (c - 1); // extra ' ' for every gap int l = left - k * (c - 1); // count for first gaps with extra '' StringBuilder sb = new StringBuilder(words[i]); for (int x = i+1; x < j; x++) { if (l > 0) { sb.append(' '); l--; } sb.append(' '); sb.append(spaces[k]); sb.append(words[x]); } result.add(sb.toString()); } } i = j; } return result; } }