13.9—动态规划—Edit Distance

来源:互联网 发布:tplink访客网络是什么 编辑:程序博客网 时间:2024/05/21 12:39
描述
Given two words word1 and word2, find the minimum number of steps required to convert word1 to
word2. (each operation is counted as 1 step.)
You have the following 3 operations permied on a word:
Insert a character
Delete a character
Replace a character

#include<iostream>#include<string>using namespace std;int mymin(int a, int b, int c){int tmp = a < b ? a : b;return tmp < c ? tmp : c;}int EditDistance(string s1, string s2){int len1 = s1.size();int len2 = s2.size();int **p = new int *[len1 + 1];for (int i = 0; i <= len1; i++)p[i] = new int[len2 + 1];for (int i = 0; i <= len1; i++)for (int j = 0; j <= len2; j++)p[i][j] = 0;for (int i = 0; i < len2; i++)p[0][i + 1] = i + 1;for (int i = 0; i < len1; i++)p[i + 1][0] = i + 1;for (int i = 1; i <= len1; i++){for (int j = 1; j <= len2; j++){if (s1[i - 1] == s2[j - 1])p[i][j] = p[i - 1][j - 1];else{p[i][j] = mymin(p[i - 1][j - 1]+1, p[i][j - 1]+1, p[i - 1][j]+1);}}}int tmp = p[len1][len2];for (int i = 0; i <= len1; i++)delete[]p[i];delete[]p;return tmp;}int main(){string s1 = "abdc";string s2 = "acde";int res = EditDistance(s1, s2);cout << res << endl;}

原创粉丝点击