字符串编辑距离问题
2014-07-24 22:45
260 查看
/* 字符串编辑问题,给定一个源字符串和目的字符串,源字符串可以insert,delete,replace,求最少操作使其变成目标字符串,有两种方法,方法一采用 动态规划方法,f[i][j]=min{f[i-1][j]+1,f[i+1][j]+1,f[i-1][j-1]+(s[i]==t[j]?0:1)}.方法二采用递归实现(这个是求相似度,意思是一样的),没有动态规划好 两个子串一个到另一的距离和另一个到它的距离是一样的。 */ #include <iostream> using namespace std; #include <string> //动态规划方法,f[i][j]表示从【0--i】和【0---j】的最小操作数, /* f[i][j]=min{f[i-1][j]+1(此为删除s[i]操作),f[i][j-1]+1(此为增加d[j]操作,f[i-1][j-1]+(s[i]==d[j]?0:1)(此为,如果s[i]==d[j],则说明相等,不用操作,否则替换操作) f[0][0]=0; f[0][j]={0,1,2,3,4,5,6,....j}; //都为插入 f[i][0]={0,1,2,3,.....i}; //都为删除 */ int minoperation(const string & sour,const string & dest) { int row=sour.size(); int colom=dest.size(); if(row==0) //直接插入或删除 return colom; if(colom==0) return row; int ** result=new int * [row+1]; if(result==NULL) { cout<<"wrong"<<endl; exit(1); } for(int i=0;i<=row;i++) { result[i]=new int[colom+1]; if(result[i]==NULL) { cout<<"wrong"<<endl; exit(1); } } for(int i=0;i<=row;i++) result[i][0]=i; for(int j=1;j<=colom;j++) result[0][j]=j; for(int i=1;i<=row;i++) for(int j=1;j<=colom;j++) { result[i][j]=min(min(result[i-1][j]+1,result[i][j-1]+1),result[i-1][j-1]+(sour[i-1]==dest[j-1]?0:1)); //注意sour[i-1]是因为sour是从0开始,而result多了开始的0. } int tmp=result[row][colom]; for(int i=0;i<=row;i++) delete[] result[i]; delete[] result; return tmp; } /* 方法二,采用递归的方法 s="ACAATCC" D="AGCATGC" 两个指针分别指向两个序列,sbegin,dbegin. */ int minoperation2(const string & sour,const string & dest,int sbegin,int send,int dbegin,int dend) { if(sbegin>send) { if(dbegin<dend) //最后没有了,只能全删除或全添加上才能一样 { return dend-dbegin+1; } else return 0; } if(dbegin>dend) { if(sbegin<send) //最后没有了,只能全删除或全添加上才能一样 { return send-sbegin+1; } else return 0; } if(sour[sbegin]==dest[dbegin]) { return minoperation2(sour,dest,sbegin+1,send,dbegin+1,dend); } else { int t1=minoperation2(sour,dest,sbegin+1,send,dbegin+1,dend); int t2=minoperation2(sour,dest,sbegin,send,dbegin+1,dend); int t3=minoperation2(sour,dest,sbegin+1,send,dbegin,dend); return min(min(t1,t2),t3)+1; } } int main() { string source="ACAATCC"; string dest="AGCATGC"; //cout<<minoperation(source,dest)<<endl; cout<<minoperation2(source,dest,0,source.size(),0,dest.size())<<endl; system("pause"); }
相关文章推荐
- 字符串编辑距离问题详解
- 动态规划问题学习路线:斐波那契数列,最大递增子序列,松鼠捡苹果,最大公共子序列,字符串编辑距离
- 编辑距离 字符串相似度问题
- 《编程之美》- 3.3 - 计算字符串相似度 即 最小编辑距离问题
- 字符串编辑距离问题
- 相近字符串的匹配--编辑距离问题
- 字符串的编辑距离
- 【dp】编辑距离问题
- 动态规划求解编辑距离问题(转)
- 算法设计课后题;编辑距离问题;注意DP的设计;
- 字符串的相似度(编辑距离)
- java实现编辑距离算法,计算字符串相似度
- zjut1381 字符串的编辑距离
- 字符串的编辑距离
- 字符串相似度算法(编辑距离算法 Levenshtein Distance)
- 王晓东 编辑距离问题
- 字符串相关算法(编辑距离,最大公共字串)C#实现版
- 字符串编辑距离的计算,及相应操作过程的打印
- 字符串编辑距离的c#实现
- 《动态规划》之--字符串比较问题(扩展距离)