編程之美3.3, 計算字串的相似性

來源:互聯網
上載者:User

給出兩個字串,通過三種操作:

1,修改一個字元

2,增加一個字元

3,刪除一個字元

一次操作,表示兩個字串的距離加1,通過三種操作,使得兩個字串最終相等,求解最少運算元,從而求得兩個字串的相似性,相似性表示為1/(距離 + 1)。比如abcdefg和abcdef距離為1(通過abcdefg刪除g一個操作),這樣相似性為1/2 = 0.5。

寫出程式。

問題分析:

在求解xabcd和xbde字串的相似性時,由於第一個字串相等,可以證明,xabcd和xbde的相似性與abcd和bde的相似性相等,這樣我們可以將問題縮減為更短的字串相似性。

如果第一個字元不相等呢?我們可以通過六種方式,讓兩個字串的第一個字元相等:

1,刪除A串的第一個字元,計算A[2,3 ... ]與B[1,2 ...]的相似性

2,刪除B串的第一個字元,計算B[2,3 ... ]與A[1,2 ...]的相似性

3,增加B[1]到A串首,計算原來的A[1,2 ...]與原來的B[2,3 ...]的相似性

4,增加A[1]到B串首,計算原來的B[1,2 ...]與原來的A[2,3 ...]的相似性

5,修改A[1]為B[1],計算原來的A[2,3 ...]與原來的B[2,3 ...]的相似性

5,修改B[1]為A[1],計算原來的A[2,3 ...]與原來的B[2,3 ...]的相似性

這樣我們可以採用遞迴的方法求解字串的相似性,代碼如下:

/* * bop_3_3.cpp * *  Created on: 2012-5-24 *      Author: ict */#include <cstdio>#include <cstdlib>#include <cstring>#include <string>#include <algorithm>using namespace std;#define MAX 100int calculate(char *a, char *b){int l1 = strlen(a);int l2 = strlen(b);//遞迴返回條件,判斷字串A和B的長度是否為0if(l1 == 0){if(l2 == 0)return 0;elsereturn l2;}if(l2 == 0){if(l1 == 0)return 0;elsereturn l1;}if(a[0] == b[0])//a[0] == b[0], we just calculate the a[1,2 ...] and the b[1,2 ...] distance{return calculate(a + 1, b + 1);}else{int t1 = calculate(a+1, b);//just delete the a[0], or just add the a[0] before the b[0]int t2 = calculate(a, b+1); //just delete the b[0], or just add the b[0] before the a[0]int t3 = calculate(a+1, b+1);//just change the a[0] to b[0], or change the b[0] to a[0]return min(min(t1, t2), t3) + 1;//return the minimal value}}int main(){char a[MAX];char b[MAX];scanf("%s", a);//input the string Ascanf("%s", b);//input the string Bprintf("%f\n", 1/(1.0 + calculate(a, b)));return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.