寻找两个字符串相似度的代码

把两个字符串变成相同的基本操作定义如下:

  1. 修改一个字符(如把 a 变成 b)
  2. 增加一个字符 (如 abed 变成 abedd)
  3. 删除一个字符(如 jackbllog 变成 jackblog)

    针对于 jackbllog 到 jackblog 只需要删除一个或增加一个 l 就可以把两个字符串变为相同。把这种操作需要的次数定义为两个字符串的距离 L, 则相似度定义为1/(L+1) 即距离加一的倒数。那么 jackbllog 和 jackblog 的相似度为 1/1+1=1/2=0.5,也就是所两个字符串的相似度是 0.5,说明两个字符串已经很接近啦。

    任意两个字符串的距离都是有限的,都不会超过他们的长度之和,算法设计中我们并不在乎通过一系列的修改后,得到的两个相同字符串是什么样子。所以每次只需一步操作,并递归的进行下一计算。获得两字符串之间距离为目的,我们可以用动态规划的方法思考问题。

    算法实现如下:

-(int) MiniNum:(int) x SetY:(int) y SetZ:(int) z
{
int tempNum;
tempNum = x;
if (y<tempNum) 
{
tempNum = y;
}
if (z<tempNum) 
{
tempNum = z;
}
return tempNum;
}
-(int) DistanceBetweenTwoString:(NSString*) strA StrAbegin:(int) strAbegin StrAend:(int) strAend StrB:(NSString*) strB StrBbegin:(int) strBbegin StrBend:(int) strBend
{
int x,y,z;
if (strAbegin>strAend)
{
if (strBbegin>strBend)
{
return 0;
}
else
{
return strBend -strBbegin +1;
}


}
if (strBbegin>strBend)
{
if (strAbegin>strAend)
{
return 0;
}
else
{
return strAend -strAbegin +1;
}

}
if ([strA characterAtIndex:(NSUInteger)(strAbegin)] == [strB characterAtIndex:(NSUInteger)(strBbegin)])
{
return [self DistanceBetweenTwoString:strA StrAbegin:strAbegin+1 StrAend:strAend StrB:strB StrBbegin: strBbegin+1 StrBend: strBend];
}
else
{
x = [self DistanceBetweenTwoString:strA StrAbegin:strAbegin+1 StrAend:strAend StrB:strB StrBbegin: strBbegin+1 StrBend: strBend];
y = [self DistanceBetweenTwoString:strA StrAbegin:strAbegin StrAend:strAend StrB:strB StrBbegin: strBbegin+1 StrBend: strBend];
z = [self DistanceBetweenTwoString:strA StrAbegin:strAbegin+1 StrAend:strAend StrB:strB StrBbegin: strBbegin StrBend: strBend];
return[self MiniNum:x SetY:y SetZ:z] +1;
}

}

    调用方式为:

NSString* strRotate = [[[NSString alloc] initWithFormat:@"2103"] autorelease];
NSString* strReRotate = [[[NSString alloc] initWithFormat:@"0123"] autorelease];

int rotateDis = [self DistanceBetweenTwoString:strRotate StrAbegin:0 StrAend:[strRotate length]-1 StrB: strReRotate StrBbegin:0 StrBend:[strReRotate length]-1];

    其中,rotateDis就是两个字符串的距离。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值