描述 | |
---|---|
知识点 | 栈 |
运行时间限制 | 10M |
内存限制 | 128 |
输入 | 输入两个字符串 |
输出 | 输出相似度,string类型 |
样例输入 | abcdef abcdefg |
样例输出 | 1/2 |
#include<iostream>
#include<string>
using namespace std;
int getMin(int a, int b, int c)
{
int minVal = b<c ? b : c;
return a<minVal ? a : minVal;
}
int calculateStringDistance(string str1, string str2, int begin1, int end1, int begin2, int end2)
{
if (begin1 > end1)
{
if (begin2 > end2)
return 0;
else
return end2 - begin2 + 1;
}
if (begin2 > end2)
{
if (begin1 > end1)
return 0;
else
return end1 - begin1 + 1;
}
if (str1[begin1] == str2[begin2])
{
return calculateStringDistance(str1,str2,begin1+1,end1,begin2+1,end2);
}
else
{
int t1 = calculateStringDistance(str1, str2, begin1 +1, end1, begin2, end2);
int t2= calculateStringDistance(str1, str2, begin1, end1, begin2+1, end2);
int t3= calculateStringDistance(str1, str2, begin1 + 1, end1, begin2+1, end2);
return(getMin(t1, t2, t3)+1 );
}
}
int main()
{
string s1,s2;
getline(cin,s1);
getline(cin, s2);
int cal=calculateStringDistance(s1, s2, 0, s1.size()-1, 0, s2.size()-1);
cout << "1/"<<cal+1<<endl;
return 0;
}
书中提到,上面的递归程序中,有些数据被重复计算了,解决方法是可以用一个string变量来放子问题;关于从网上看到
int t1 = calculateStringDistance(str1, str2, begin1 +1, end1, begin2, end2);
int t2= calculateStringDistance(str1, str2, begin1, end1, begin2+1, end2);
int t3= calculateStringDistance(str1, str2, begin1 + 1, end1, begin2+1, end2);
这部分变成
int t1 = calculateStringDistance(str1, str2, begin1 +2, end1, begin2+1, end2);
int t2= calculateStringDistance(str1, str2, begin1+1, end1, begin2+2, end2);
int t3= calculateStringDistance(str1, str2, begin1 + 2, end1, begin2+2, end2);
表示费解,直接跳过了进行下一组对比,不是很能理解。
动态规划的解法下回再补充,还不是很会dp.