LeetCode 68题是“文本左右对齐”问题。我们需要将给定的单词列表格式化为指定的宽度,并对齐文本。以下是Java解题代码,并附上每行代码的注释:
import java.util.ArrayList;
import java.util.List;
public class TextJustification {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> result = new ArrayList<>(); // 创建一个列表来存储结果字符串
int index = 0; // 初始化索引为0
while (index < words.length) { // 遍历所有单词
int count = words[index].length(); // 当前行的第一个单词长度
int nextIndex = index + 1; // 下一个单词的索引
// 尝试将尽可能多的单词放入当前行
while (nextIndex < words.length) {
if (words[nextIndex].length() + count + 1 > maxWidth) break; // 如果加上下一个单词和一个空格超过了最大宽度,则停止
count += words[nextIndex].length() + 1; // 增加当前行的长度
nextIndex++; // 移动到下一个单词
}
StringBuilder builder = new StringBuilder(); // 创建一个字符串构建器