Algorithms first
文本左右对齐 · 交互式算法学习
把单词排成每行恰好 maxWidth 字符的左右对齐文本。
#68 · 数组 / 字符串
文本左右对齐
Text Justification
words = ["This","is","an","example"], maxWidth = 16线性序列3 个关键状态
步骤 1扫描器确定当前行单词。
size=8This
0is
1an
2推荐
统一行格式化器
时间
O(字符总数)空间 O(maxWidth)扫描负责确定行边界,独立格式化器处理普通行与最后一行。
1function justify(line, width, last) {2 if (last || line.length === 1) return line.join(' ').padEnd(width);3 const letters = line.reduce((n, w) => n + w.length, 0),4 gaps = line.length - 1;5 const q = Math.floor((width - letters) / gaps),6 r = (width - letters) % gaps;7 return line.map((w, i) => i < gaps ? w + ' '.repeat(q + (i < r ? 1 : 0)) : w).join('');8}9 10function fullJustify(words, width) {11 const out = [];12 let line = [],13 size = 0;14 for (const w of words) {15 if (size + w.length + line.length > width) {16 out.push(justify(line, width, false));17 line = [];18 size = 0;19 }20 line.push(w);21 size += w.length;22 }23 out.push(justify(line, width, true));24 return out;25}多语言参考
来源 · CC BY-SA 4.0 ↗Java · C++ · Go
这是一组同题正确实现,独立于上方当前动画方法;不同语言可能采用另一种正确策略。
1class Solution {2 public List<String> fullJustify(String[] words, int maxWidth) {3 List<String> ans = new ArrayList<>();4 for (int i = 0, n = words.length; i < n;) {5 List<String> t = new ArrayList<>();6 t.add(words[i]);7 int cnt = words[i].length();8 ++i;9 while (i < n && cnt + 1 + words[i].length() <= maxWidth) {10 cnt += 1 + words[i].length();11 t.add(words[i++]);12 }13 if (i == n || t.size() == 1) {14 String left = String.join(" ", t);15 String right = " ".repeat(maxWidth - left.length());16 ans.add(left + right);17 continue;18 }19 int spaceWidth = maxWidth - (cnt - t.size() + 1);20 int w = spaceWidth / (t.size() - 1);21 int m = spaceWidth % (t.size() - 1);22 StringBuilder row = new StringBuilder();23 for (int j = 0; j < t.size() - 1; ++j) {24 row.append(t.get(j));25 row.append(" ".repeat(w + (j < m ? 1 : 0)));26 }27 row.append(t.get(t.size() - 1));28 ans.add(row.toString());29 }30 return ans;31 }32}交互式算法学习
从执行步骤真正理解 LeetCode 经典 150
本站整理 150 道高频算法面试题和 302 种解法。动画方法同步展示 JavaScript 与 Python;每题另提供 Java、C++ 与 Go 同题参考实现。
AlgoViz Lab
文本左右对齐 · 解法对比
把单词排成每行恰好 maxWidth 字符的左右对齐文本。
- 测试用例
words = ["This","is","an","example"], maxWidth = 16- 题目分类
- 数组 / 字符串
- 解法对比
- 2
逐行收集再分配空格
贪心装入尽量多的单词,再把空格平均分配到间隔。
- 时间
O(字符总数)- 空间
O(maxWidth)
统一行格式化器
扫描负责确定行边界,独立格式化器处理普通行与最后一行。
- 时间
O(字符总数)- 空间
O(maxWidth)
为什么有效
贪心装入尽量多的单词,再把空格平均分配到间隔。
关键不变量
每一步都保持当前方法的已处理部分正确,并朝“把单词排成每行恰好 maxWidth 字符的左右对齐文本。”推进。
易错点
- 先确认输入边界与下标范围。
- 代码、变量状态与动画步骤应保持一致。
边界情况
- 空输入或最小规模输入。
- 重复值、极端顺序或退化结构。
更多案例
words = ["This","is","an","example"], maxWidth = 16把单词排成每行恰好 maxWidth 字符的左右对齐文本。贪心装入尽量多的单词,再把空格平均分配到间隔。