68. 文本对齐 | LeetCode | Top Interview 150 | Coding Questions
发布: (2025年12月29日 GMT+8 05:53)
2 min read
原文: Dev.to
Source: Dev.to
问题
解决方案(Java)
class Solution {
public List fullJustify(String[] words, int maxWidth) {
List result = new ArrayList<>();
int n = words.length;
int index = 0;
while (index < n) {
int totalChars = words[index].length();
int last = index + 1;
while (last < n && totalChars + 1 + words[last].length() <= maxWidth) {
totalChars += 1 + words[last].length();
last++;
}
StringBuilder sb = new StringBuilder();
int diff = last - index - 1;
if (last == n || diff == 0) {
for (int i = index; i < last; i++) {
sb.append(words[i]);
if (i < last - 1) {
sb.append(" ");
}
}
int remainingSpaces = maxWidth - sb.length();
appendSpaces(sb, remainingSpaces);
} else {
int spaces = (maxWidth - totalChars) / diff;
int extraSpaces = (maxWidth - totalChars) % diff;
for (int i = index; i < last; i++) {
sb.append(words[i]);
if (i < last - 1) {
int spacesToApply = spaces + (i - index < extraSpaces ? 1 : 0);
appendSpaces(sb, spacesToApply + 1);
}
}
}
result.add(sb.toString());
index = last;
}
return result;
}
private void appendSpaces(StringBuilder sb, int count) {
for (int i = 0; i < count; i++) {
sb.append(" ");
}
}
}