博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

计算字符串的相似度

Posted on 2011-08-22 20:44  ChessYoung  阅读(308)  评论(0编辑  收藏  举报

许多程序会大量使用字符串。对于不同的字符串,我们希望能够有办法判断其相似程序。我们定义一套操作方法来把两个不相同的字符串变得相同,具体的操作方法为:

  1.修改一个字符(如把“a”替换为“b”);

  2.增加一个字符(如把“abdd”变为“aebdd”);

  3.删除一个字符(如把“travelling”变为“traveling”);

  比如,对于“abcdefg”和“abcdef”两个字符串来说,我们认为可以通过增加/减少一个“g”的方式来达到目的。上面的两种方案,都仅需要一 次 。把这个操作所需要的次数定义为两个字符串的距离,而相似度等于“距离+1”的倒数。也就是说,“abcdefg”和“abcdef”的距离为1,相似度 为1/2=0.5。

  给定任意两个字符串,你是否能写出一个算法来计算它们的相似度呢?

#include "stdafx.h"
#include
<iostream>
#include
<assert.h>
#include
<string>
#include
<math.h>
#include
<vector>
using namespace std;

int CalculateStringDistance(char *s1, char *s2);

int _tmain(int argc, _TCHAR* argv[])
{
int distance = 0;
char *s1 = "travelling";
char *s2 = "traveling";
distance
= CalculateStringDistance(s1, s2);
double similar = 1.0/(distance+1);

cout
<< similar << endl;

return 0;
}

int CalculateStringDistance( char *s1, char *s2 )
{
int dis = 0;
int len1 = strlen(s1);
int len2 = strlen(s2);
if (len2 > len1)
{
len1
^= len2;
len2
^= len1;
len1
^= len2;
}
dis
+= len1-len2;

for (int i = 0;i<len2;i++)
{
if (*s1 != *s2)
{
dis
++;
}
}
return dis;
}