题目:计算字符串的相似度
描述 | |
---|---|
知识点 | 栈 |
运行时间限制 | 10M |
内存限制 | 128 |
输入 |
输入两个字符串 |
输出 |
输出相似度,string类型 |
样例输入 | abcdef abcdefg |
样例输出 | 1/2 |
1第一种是《编程之美》中基于递归的,他们说有重复的情况,我也不明白肿么重复了。
int calStringDis(string strA, int pABegin,int pAEnd,string strB, int pBBegin,int pBEnd)
{
if (pABegin > pAEnd)
{
if (pBBegin > pBEnd)
return 0;
else
return pBEnd - pBBegin + 1;
}
if (pBBegin > pBEnd)
{
if(pABegin > pAEnd)
return 0;
else
return pAEnd - pABegin + 1;
}
if (strA[pABegin] == strB[pBBegin])
{
return calStringDis(strA,pABegin+1,pAEnd,strB,pBBegin+1,pBEnd);
}
else
{
int t1 = calStringDis(strA,pABegin+1,pAEnd,strB,pBBegin+2,pBEnd);
int t2 = calStringDis(strA,pABegin+2,pAEnd,strB,pBBegin+1,pBEnd);
int t3 = calStringDis(strA,pABegin+2,pAEnd,strB,pBBegin+2,pBEnd);
return minValue(t1,t2,t3)+1;
}
}
2第二种是动态规划,和最长公共子序列类似,感觉两种方法思路没有什么区别。
#include<iostream>
#include<string>
using namespace std;
int calculateDist(string,string);
int min_value(int,int,int);
int main()
{
string s1,s2;
cin>>s1;
cin>>s2;
cout<<"1/"<<(1+calculateDist(s1,s2))<<endl;
//system("pause");
return 0;
}
int calculateDist(string s1,string s2)
{
int len1=s1.size()+1;
int len2=s2.size()+1;
int **cnt=new int*[len1];
for(int i=0;i<len1;++i)
cnt[i]=new int[len2];
for(int i=0;i<len1;++i)
cnt[i][0]=i;
for(int j=0;j<len2;++j)
cnt[0][j]=j;
for(int i=1;i<len1;++i)
for(int j=1;j<len2;++j)
if(s1[i-1]==s2[j-1])
cnt[i][j]=cnt[i-1][j-1];
else
cnt[i][j]=min_value(cnt[i-1][j-1],cnt[i-1][j],cnt[i][j-1])+1;
int num=cnt[len1-1][len2-1];
for(int i=0;i<len1;++i)
delete [] cnt[i];
delete [] cnt;
return num;
}
int min_value(int a,int b,int c)
{
int min;
if(a<b)
min=a;
else
min=b;
if(min>c)
min=c;
return min;
}