算法

编辑距离(Levenshtein)

比较两个字符串,观察 Levenshtein 矩阵的填充。最后一个格子就是把一个字符串变成另一个所需的最少编辑次数。

8 分钟难度 3/3交互演示区域不展示广告。
Try:Case matters · max 10 characters
FromkittenTosittingDistance3Cell6, 7
∅sitting
∅01234567
k11234567
i22123456
t33212345
t44321234
e55432234
n66543323

This cell kitten → sitting: 3

Characters differ: choose the cheapest operation.

↖ replace/match 4↑ delete 5← insert 3

Distance: 3

k → se → iinsert g

A diagonal move is a match (cost 0) or a replace (cost 1). Horizontal and vertical moves are insert and delete. The highlighted path is one optimal edit sequence. Edit either word to turn this into a reusable tool; ties prefer the diagonal.

你看到的是什么

1

行和列分别是两个字符串的前缀。每个格子保存这两个前缀之间的编辑距离。

2

当前字符相同则继承对角线值;不同则取插入、删除、替换三者最小值加一。

3

右下角就是答案。回溯还能还原具体的编辑操作序列。

为什么重要

编辑距离用于拼写检查、DNA 比对、模糊搜索和 diff 工具,也是二维动态规划的清晰例子。

复杂度与细节

时间:O(mn);完整矩阵空间:O(mn)(滚动行可降到 O(min(m,n)))。

常见问题

什么算一次编辑?+

插入一个字符、删除一个字符或替换一个字符。替换字符算一次操作。

编辑距离用在哪里?+

拼写纠错、DNA 序列比对、抄袭检测、模糊匹配和版本控制 diff 都使用编辑距离的变体。