您的位置:首页 > 其它

有关字符串匹配的算法

2014-07-29 14:11 417 查看
1、KMP算法

july的博客已经写的很详细了。

2、BM算法

july的博客也有,具体可以参考阮一峰的博客,但是没有坏字符表和好后缀表的实现。

3、sunday算法

还有字符串匹配算法总结的,这里给个java实现,求共勉

public static int sunday(String pattern, String str){

if (pattern == null || str == null || str.length() == 0){
return -1;
}

int patLen = pattern.length();
int strLen = str.length();

//计算模式串中每个字符距离最右边字符的最近距离,字符仅限于ascii字符
int[] charPosition = new int[256];
//初始化每个字符的距离为:模式串长度+1,表示当母串中和模式串对应的最后一个字符的下一个字符
//没有出现在模式串中,母串当前索引需要向右移动:模式串长度+1。
for (int i = 0; i < 256; i++){
charPosition[i] = patLen +1;
}
//开始计算每个字符的距离
for (int i = 0; i < patLen; i++){
charPosition[(int)pattern.charAt(i)] = patLen - i;
}

//开始匹配
int strIndex = 0;
int patIndex = 0;
while (strIndex < strLen){
//保存每一次失配后母串中和模式串对应的起始字符的位置,作为以后移动距离的起始点
int startMove = strIndex;
while (patIndex < patLen){
if (str.charAt(strIndex) == pattern.charAt(patIndex)){
strIndex++;
patIndex++;
continue;
}else{
//如果母串中找不到与模式串对应的最后一个字符的下一个字符,则不匹配返回。
int dis = startMove + patLen;
if (dis > strLen){
return -1;
}
//如果能找到,则母串移动相应距离,模式串重新开始匹配
char ch = str.charAt(dis);
dis = charPosition[(int)ch];
strIndex = startMove + dis;
patIndex = 0;
break;
}
}
if (patIndex == patLen){
return strIndex - patLen;
}
}
return -1;
}


4、字符串全排列和组合

递归和非递归
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: