兩個字串的編輯距離動態規劃求解(C語言版)

2021-10-03 04:26:53 字數 1083 閱讀 6622

問題描述

(a)執行一次刪除操作,編輯距離加1

(b)執行一次刪除操作,編輯距離加1

(c)修改乙個字元,編輯距離加1

例如testing修改為kestan的編輯距離為3,即最少操作次數

問題求解

(a)需要用到乙個二維矩陣dist[len1 + 1][len2 + 1],len1、len2分別為兩個字串的長度。

(b)dis[i][j]是指str1[i]和str2[j]的最短編輯距離,顯然有:

for(i = 0; i <= len1; i++) dist[i][0] = i;

for(j = 0; j <= len2; j++) dist[0][j] = j;

(c)分析規定的三個操作:新增,刪除,替換。

x = dist[i],y = dist[j]

if x == y, then dist[i][j] == dist[i-1][j-1]

if x != y, and we insert y for str1, then dist[i][j] = dist[i][j-1] + 1

if x != y, and we delete x for str1, then dist[i][j] = dist[i-1][j] + 1

if x != y, and we replace x with y for str1, then dp[i][j] = dp[i-1][j-1] + 1

when x!=y, dist[i][j] is the min of the three situations.

c語言**

#include

#include

intmin

(int a,

int b,

int c)

intmychardistance

(char str1,

char str2)

}return dist[len1]

[len2];}

intmain()

兩個字串的編輯距離 動態規劃

字串的編輯距離,又稱為levenshtein距離,由俄羅斯的數學家vladimir levenshtein在1965年提出。是指利用字元操作,把字串a轉換成字串b所需要的最少運算元。其中,字元操作包括 1 刪除乙個字元 2 插入乙個字元 3 修改乙個字元 3 如果不一樣,那麼必定要經過一次操作 編輯...

求兩個字串的距離

給定兩個長度相等的,由小寫字母組成的字串s1和s2,定義s1和s2的距離為兩個字串有多少個位置上的字母不相等。現在牛牛可以選定兩個字母x1和x2,將s1中的所有字母x1均替換成x2。x1和x2可以相同 牛牛希望知道執行一次替換之後,兩個字串的距離最少為多少。x1和x2是自己求的,未知 輸入 aaa ...

兩個字串的最短串編輯距離

假定有兩個字串s1,s2,求出由s1變為s2所需要花費的最小代價。刪除乙個字元的代價為1,增加乙個字元的代價為2,替換乙個字元的代價為2。比如由 abc 變為 abe 你可以刪除c,然後新增e,這樣代價是3 也可以將c替換成e,這樣代價是2,顯然2比較小。具體串編輯問題請參閱演算法書籍。本 運用的是...