---
title: "编辑距离"
author: "SwordAndFlame"
date: "2011-08-05T18:20:38Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-08-05T18:20:38Z"
id: 1141271
url: "https://swordandflame.iteye.com/blog/1141271"
---

编辑距离;

来自wiki的编辑距离介绍

**编辑距离** ，又称**Levenshtein距离** ，是指两个[字串](http://zh.wikipedia.org/wiki/%E5%AD%97%E4%B8%B2 "字串") 之间，由一个转成另一个所需的最少编辑操作次数。许可的编辑操作包括将一个字符替换成另一个字符，插入一个[字符](http://zh.wikipedia.org/wiki/%E5%AD%97%E7%AC%A6 "字符") ，删除一个字符。

例如将kitten一字转成sitting：

1. sitten （k→s）
2. sittin （e→i）
3. sitting （→g）

[俄罗斯](http://zh.wikipedia.org/wiki/%E4%BF%84%E7%BE%85%E6%96%AF "俄罗斯") 科学家[Vladimir Levenshtein](http://zh.wikipedia.org/w/index.php?title=Vladimir_Levenshtein&action=edit&redlink=1 "Vladimir Levenshtein") 在[1965年](http://zh.wikipedia.org/wiki/1965%E5%B9%B4 "1965年") 提出这个概念。

编辑距离的经典动态规划算法：

初始化：

字符串 Levenshtein距离(字符 str1\[1..lenStr1], 字符 str2\[1..lenStr2])  
    char d\[0..lenStr1, 0..lenStr2]  
    int i, j, cost  
   
   for i  0 -&gt; lenStr1  
       d\[i, 0] := i  
  for j   0 -&gt; lenStr2  
       d\[0, j] := j

dp求解：

for  i 1 -&gt; lenStr1  
        for j 1 -&gt; lenStr2

            if str1\[i] = str2\[j]  
            then cost := 0  
           else cost := 1  
           d\[i, j] := min(  
                                 d\[i-1, j  ] + 1,     // 刪除  
                                d\[i  , j-1] + 1,     // 插入  
                                d\[i-1, j-1] + cost   // 替換  
                                )  
 return d\[lenStr1, lenStr2]