編輯距離演算法(Edit Distance)

2021-08-21 10:56:18 字數 3291 閱讀 7547

概念

編輯距離又稱levenshtein距離,是指兩個字串之間,由乙個轉成另乙個所需的最少編輯操作次數。

許可的編輯操作包括

問題描述

給定兩個字串str1和str2,str1至少經過多少步字元操作變成str2,只有插入,刪除,替換這三種操作 。

比如要計算cafe和coffee的編輯距離。cafe→caffe→coffe→coffee ,最少經過3步操作cafe才能變成coffee,即編輯距離為3。

演算法思路

一般情況,可以把問題看作用最少步驟將 str1[1…i] 轉化為 str2[1…j]。

若要str1[1…i] 轉化為 str2[1…j]步驟最少,則需滿足下面三種情況之一:

1、str1[1…i-1] 轉化為 str2[1…j] 的步驟最少,記總算子為k。

2、str1[1…i] 轉化為 str2[1…j-1] 的步驟最少,記總算子為m。

3、str1[1…i-1] 轉化為 str2[1…j-1] 的步驟最少,記總算子為n。

若滿足情況1,還需執行一步操作,刪除str1[i],所以總最少運算元為 k+1,

若滿足情況2,還需執行一步操作,在str1後插入str2[j],所以總最少運算元為 m+1,

若滿足情況3,還需要分兩種情況:

演算法步驟

以cafe—>coffee為例,先初始化乙個二維陣列co

ffee

01234

56c1

a2f3

e4cafe為源字串,coffee為目標字串。

數字代表從源字串到目標字串的編輯距離,如二行三列的1 表示從源字串的空白,到目標字串的『c』,距離為1(插入乙個』c』),其餘同理。co

ffee

0123

456c

1012

345a

2f3e

4填入第三列數字,每一格的數字,

​ 左邊數字表示 str1[1…i] 轉化為 str2[1…j-1] 的步數

​ 上邊數字表示 str1[1…i-1] 轉化為 str2[1…j] 的步數

​ 左上數字表示 str1[1…i-1] 轉化為 str2[1…j-1] 的步數

所以取左上,左,上 三個數最小的,若左上最小,則判斷最左邊與最上方字元是否相同,則此格數字等於左上方數字,否則,此格數字則為其+1co

ffee

0123

456c

1012

345a

2112

345f

3221

234e

4332

223

取最後一格就是源字串到目標字串的編輯距離 3。

實現**(python)

def

editdist

(s1, s2)

: m, n =

len(s1)+1

,len

(s2)+1

# 建立二維陣列

array =[[

0]*n for i in

range

(m)]

# 初始化

for i in

range(1

, m)

: array[i][0

]= array[i-1]

[0]+

1for i in

range(1

, n)

: array[0]

[i]= array[0]

[i-1]+

1# 實現

for i in

range(1

, m)

:for j in

range(1

, n)

:if s1[i-1]

!= s2[j-1]

: cost =

1else

: cost =

0 array[i]

[j]=

min(array[i-1]

[j]+

1, array[i]

[j-1]+

1, array[i-1]

[j-1

]+ cost)

return array[m-1]

[n-1

]res = editdist(

'cafe'

,'coffee'

)print

(res)

複雜度分析

時間複雜度為o(mn),因為用到二維陣列來儲存狀態,所以空間複雜度也為o(mn)

空間優化

因為這個演算法只需要上一行和當前行被儲存下來就可以了, 可以將其改進為o(n)。

def

editdist

(s1, s2)

: m, n =

len(s1)+1

,len

(s2)+1

# 建立兩個長度為n的一維陣列

cur =[0

]*nnext=[

0]*n # 初始化

for i in

range(1

, n)

: cur[i]

= cur[i-1]

+1# 實現

for i in

range(1

, m)

:next[0

]= i

for j in

range(1

, n)

:if s1[i-1]

!= s2[j-1]

: cost =

1else

: cost =

0next

[j]=

min(cur[j]+1

,next

[j-1]+

1, cur[j-1]

+cost)

cur =

next[:

:]# 深拷貝

return

next[-

1]res = editdist(

'cafe'

,'coffee'

)

編輯距離及編輯距離演算法

編輯距離概念描述 編輯距離,又稱levenshtein距離,是指兩個字串之間,由乙個轉成另乙個所需的最少編輯操作次數。許可的編輯操作包括將乙個字元替換成另乙個字元,插入乙個字元,刪除乙個字元。例如將kitten一字轉成sitting sitten k s sittin e i sitting g 俄...

編輯距離及編輯距離演算法

include include include using namespace std const int max 1001 int maxlen max max int maxlen string str1,string str2 return maxlen len1 len2 int main ...

編輯距離及編輯距離演算法

include include include using namespace std const int max 1001 int maxlen max max int maxlen string str1,string str2 return maxlen len1 len2 int main ...