計算最小編輯距離
阿新 • • 發佈:2019-01-30
#include <iostream> #include <vector> #include <string> #include <cmath> #include <algorithm> using namespace std; int levenShtein(string s1,string s2) { int cel=s1.size(); int row=s2.size(); if(cel==0) return row; if(row==0) return cel; vector<vector<int>> vec(row+1,vector<int>(cel+1)); for(int i=0;i<=cel;i++) vec[0][i]=i; for(int j=0;j<=row;j++) vec[j][0]=j; for(int r=1;r<=row;r++) { for(int c=1;c<=cel;c++) { int cost=0; if(s1[r-1]==s2[c-1]) cost=0; else cost=2; //susstitution cost 2 //D[i,j]=min(D[i-1,j]+1,D[i,j-1]+1,D[i,j]+cost) vec[r][c]=min(min(vec[r-1][c]+1,vec[r][c-1]+1),vec[r-1][c-1]+cost); } } return vec[row][cel]; } int main() { string s1("execution"); string s2("intention"); cout<<levenShtein(s1,s2)<<endl; }