動態規劃求解編輯距離問題

來源:互聯網
上載者:User

題目描述:

要求兩字串有差異的字元個數。例如:
aaaaabaaaaa
aaaaacaabaa
這兩個字串,最大公用字串長度是5,但它們只有兩個字元不同,函數輸出值應為2。
如果是:
aaabbbcccddd
aaaeeeddd
函數的輸出值應該是6。

比較形象地形容一下,把兩個字串排成上下兩行,每個字串都可以在任何位置插入空格以便上下對齊,每個列上至少有一個字元來自這兩個字串。當對齊程度最高的時候,沒有對上的列的數即為函數輸出值。
aaabbbcccddd
aaaeeeddd
最優對齊狀態是:
aaabbbcccddd
aaaeee     ddd
沒有對上的列是6,函數輸出值為6。
如果是:
abcde
acefg
最優對齊狀態是:
abcde
a  c  efg
沒有對上的列數是4,函數輸出值為4。

 

 

問題抽象歸類:(編輯距離問題)

設A和B是2個字串。要用最少的字元操作將字串A轉換為字串B。這裡所說的字元操作包括:

(1)刪除一個字元;
(2)插入一個字元;
(3)將一個字元改為另一個字元。
將字串A變換為字串B所用的最少字元運算元稱為字串A到B的編輯距離,記為d(A,B)。試設計一個有效演算法,對任給的2個字串A和B,計算出它們的編輯距離d(A,B)。
要求:
輸入:第1行是字串A,第2行是字串B。
輸出:字串A和B的編輯距離d(A,B)

 

 

思路:動態規劃

開一個二維數組d[i][j]來記錄a0-ai與b0-bj之間的編輯距離,要遞推時,需要考慮對其中一個字串的刪除操作、插入操作和替換操作分別花費的開銷,從中找出一個最小的開銷即為所求

具體演算法:

首先給定第一行和第一列,然後,每個值d[i,j]這樣計算:d[i][j]   =   min(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]+(s1[i]  ==  s2[j]?0:1));  
 最後一行,最後一列的那個值就是最小編輯距離 

 

 

代碼:

  1. #include <stdio.h>   
  2. #include <string.h>   
  3. char s1[1000],s2[1000];   
  4. int min(int a,int b,int c) {   
  5.     int t = a < b ? a : b;   
  6.     return t < c ? t : c;   
  7. }   
  8. void editDistance(int len1,int len2) {   
  9.     int** d=new int*[len1+1];
        for(int k=0;k<=len1;k++)
            d[k]=new int[len2+1];  
  10.     int i,j;   
  11.     for(i = 0;i <= len1;i++)   
  12.         d[i][0] = i;   
  13.     for(j = 0;j <= len2;j++)   
  14.         d[0][j] = j;   
  15.     for(i = 1;i <= len1;i++)   
  16.         for(j = 1;j <= len2;j++) {   
  17.             int cost = s1[i] == s2[j] ? 0 : 1;   
  18.             int deletion = d[i-1][j] + 1;   
  19.             int insertion = d[i][j-1] + 1;   
  20.             int substitution = d[i-1][j-1] + cost;   
  21.             d[i][j] = min(deletion,insertion,substitution);   
  22.         }   
  23.     printf("%d/n",d[len1][len2]); 
  24.     for(int k=0;i<=len1;k++)
            delete[] d[k];
        delete[] d;
  25. }   
  26. int main() {   
  27.     while(scanf("%s %s",s1,s2) != EOF)   
  28.         editDistance(strlen(s1),strlen(s2));   
  29. }  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.