代码分享,寻找两个字符串的相似度。 ios版本
来源:互联网 发布:des算法f函数 编辑:程序博客网 时间:2024/06/06 19:19
把两个字符串变成相同的基本操作定义如下:
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就是两个字符串的距离!
- 代码分享,寻找两个字符串的相似度。 ios版本
- 寻找两个字符串相似度的代码
- 计算两个字符串的距离(相似度)
- 比较两个字符串的相似度
- 计算两个字符串相似度的算法
- java两个字符串的相似度
- C#计算两个字符串的相似度
- oracle比较两个字符串的相似度
- 检查两个字符串的相似度
- 比较两个字符串的相似度
- PHP 比较两个字符串的相似度
- 比较两个字符串的相似度
- 华为OJ-----两个字符串的相似度
- java代码比较两个字符串的相似程度
- SQL的两个字符串的相似度的计算函数
- 求两个字符串的相似度(或距离)
- 编程之美3.3 计算两个字符串的相似度
- SQL_函数比较两个字符串的相似度
- VS2010 VS2005 VS2008工程之间的转换
- 选修课:唐宋词鉴赏课堂笔记03
- MVS子进程进度实时显示
- 在DataSet中处理字段中的NULL问题入门6
- design
- 代码分享,寻找两个字符串的相似度。 ios版本
- 如何在DLL的输出函数中返回字符串给调用者
- 显卡结构与工作原理解读
- TMS320F2812产生PWM波程序
- 在DataSet中实现纪录删除的自定义方法入门7
- F2812中程序从Flash中搬运到SRAM中运行加快速度
- iReport group 控件使用方法
- HMM的资源大部分重复
- 设计放大器