来自《编程之美》3.3
题目:定义了三种不同的操作把不同的字符串变成相同
1.修改一个字符;
2.增加一个字符;
3.删除一个字符;
为了把两个字符串变得相同,每进行一次上述的某个操作,距离加1,最后定义两个字符串的相似度为“距离+1”的倒数。要求求出任意两个字符串的相似度。
解法:
#include<iostream> usingnamespace std; //来自编程之美3.3题,书上是用递归的方式实现的,我尝试用循环的方式 double getStrSiminarity(string str1, string str2) { int len1, len2; len1 = str1.length(); len2 = str2.length(); if(len1 ==0|| len2 ==0) return0.0; //let tmp1 longer than or equal to tmp2 string tmp1,tmp2; if(len1>=len2){ tmp1 = str1; tmp2 = str2; } else{ tmp1 = str2; tmp2 = str1; } int index1 =0; int index2 =0; double distance =0; while(index1<len1 || index2<len2){ if(index2 == len2){ distance += tmp1.substr(index1).length(); break; } if(tmp1[index1]== tmp2[index2]){ index1++; index2++; } else{ if(tmp1.length()== tmp2.length()){ distance ++; index1++; index2++; } else{//if tmp1 is longer than tmp2,just erase this char tmp1 = tmp1.erase(index1,1); distance++; } } } return1/(distance+1); } int main() { string str1 ="abdd"; string str2 ="aebdd"; string str3 ="travelling"; string str4 ="traveling"; string str5 ="abcdefg"; string str6 ="abcdef"; string str7 ="xabcda"; string str8 ="xfdfa"; double test1 = getStrSiminarity(str1, str2);//0.5 double test2 = getStrSiminarity(str3, str4);//0.5 double test3 = getStrSiminarity(str5, str6);//0.5 double test4 = getStrSiminarity(str7, str8);//0.2 cout<< test1 <<" "<<test2<<" "<< test3 <<" "<<test4<<endl; return0; }