leetcode 0068
说明
只是为了记录一下,不求多快,也不深究。
会简要描述思路,代码中不写注释。
如碰到不会做的用了别人代码会在博客中标出。
题目描述
思路
这题有点烦人,花了好长时间。
就一个个往里加,单词个数确定后在添加空格,加到长度为maxWidth为止。
不想多说了,这题烦的一批。
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
StringBuilder sb = new StringBuilder();
List<String> ls = new ArrayList<String>();
int i = 0;
int count = 0;
while (true) {
if (sb.length() == 0) {
sb.append(words[i]);
count++;
i++;
continue;
}
if (i < words.length && sb.length() + words[i].length() + 1 <= maxWidth) {
sb.append(" " + words[i]);
count++;
i++;
continue;
} else {
if (count == 1 || i == words.length) {
while (sb.length() < maxWidth) {
sb.append(' ');
}
ls.add(sb.toString());
sb.delete(0, sb.length());
count = 0;
if (i == words.length) {
break;
}
continue;
} else {
int countSpace = maxWidth - sb.length();
int a = countSpace / (count - 1);
String spaces = " ";
while (spaces.length() <= a) {
spaces = spaces + " ";
}
String s = sb.toString();
s = s.replace(" ", spaces + " ");
while (s.length() > maxWidth) {
int place = s.lastIndexOf(spaces + " ");
StringBuilder sb2 = new StringBuilder(s);
sb2 = sb2.replace(place, place + 1, "");
s = sb2.toString();
}
ls.add(s);
sb.delete(0, sb.length());
count = 0;
continue;
}
}
}
return ls;
}
}