標籤:
原文:http://m.blog.csdn.net/blog/cqs_2012/17849877
有兩個字串A和B,對A可以進行如下的操作:插入一個字元,刪除一個字元,替換一個字元。問A可以通過最少多少次操作變為B?我們定義這個結果為字串的最小編輯距離。
- 思路(借鑒九章演算法的,感覺挺好,所以實現,共同學習)
字串編輯距離歸為DP題目,所以還是超好的
1 for(int i = 0;i<int(b.size()+1);i++) 2 dp[i] = new int[a.size()+1]; 3 for(int i = 0; i<int(a.size()+1);i++) 4 dp[0][i] = i; 5 for(int i = 1; i<int(b.size()+1);i++) 6 dp[i][0] = i; 7 for(int i = 1; i<int(b.size()+1);i++) 8 for(int j=1; j<int(a.size()+1);j++) 9 if( a[j-1] != b[i-1] )10 dp[i][j] = min (dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1;11 else 12 dp[i][j] = min (dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]);13 return dp[b.size()][a.size()];
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 5 // get the minest number of three numbers 6 int min(int a,int b,int c); 7 8 // get the minest distance of string a and b 9 int zifuchuan_bianji_juli(string a,string b);10 11 12 int main()13 {14 string a,b;15 cout<<"please input string a and b"<<endl;16 cin>>a>>b;17 cout<<"a=\""<<a<<"\",b=\""<<b<<"\""<<endl;18 cout<<"字串距離為: "<<zifuchuan_bianji_juli(a,b)<<endl;19 system("pause");20 return 0;21 }22 23 int zifuchuan_bianji_juli(string a,string b)24 {25 if( a.empty() )26 return int( b.size() );27 else if( b.empty())28 return int( a.size() ) ;29 30 int ** dp = new int*[ b.size()+1 ];31 for(int i = 0;i<int(b.size()+1);i++)32 dp[i] = new int[a.size()+1]; 33 for(int i = 0; i<int(a.size()+1);i++)34 dp[0][i] = i;35 for(int i = 1; i<int(b.size()+1);i++)36 dp[i][0] = i;37 for(int i = 1; i<int(b.size()+1);i++)38 for(int j=1; j<int(a.size()+1);j++)39 if( a[j-1] != b[i-1] )40 dp[i][j] = min (dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1;41 else 42 dp[i][j] = min (dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]);43 return dp[b.size()][a.size()];44 }45 46 int min(int a,int b,int c)47 {48 if(a>b)49 {50 if(b>c)51 return c;52 else return b;53 }else if(a>c)54 return c;55 else return a;56 }
【轉】字串編輯距離