字符串匹配之Sunday算法的实现
说一下主要思路:
首先,从头开始匹配.每次检查到不匹配时不是向暴力算法那样直接往后移动一位完事.而是遵循以下规则: (为了直观用例子说明)
源串:codzfor
查找:def
第一次从头开始查找,c!=d 匹配失败,看源串中本次匹配结尾位置的后一个字母z,
-
如果z在查找串(def)中没出现,直接将查找串往后移动4个长度变成下面这样:
codzfor
------def
4=3+1=查找串长度+1 -
如果z在查找串出现了,取最后一次出现的索引index,移动查找串长度-index,如下面这个例子:
codefor
def
c!=d不匹配,e在def中的索引是1(从0开始的),所以移动2个长度变成这样:
codefor
—def
其中2=3-1=模式串长度-索引
移动之后就可以进行接着匹配了,直到匹配成功或者尝试到源串结尾还没有匹配成功.
/**
* Sunday 算法
* 本函数用于在源字符串中查找模式字符串的位置
*
* @param src 源字符串
* @param pat 模式字符串
* @return 模式字符串在源字符串的索引起始位置,未找到为-1
*/
public static int Sunday(String src,String pat){
if(src.length()<pat.length()) return -1;
int start = 0;//
int end = start + pat.length() - 1;//
while(end < src.length()) {
int i = 0;
for (; i < pat.length(); i++) {
if (src.charAt(start + i) == pat.charAt(i)) {
//do nothing
} else {
break;
}
}
if (i == pat.length()) {//匹配成功
return start;
}
//没找到,移动模式串的位置
if (end + 1 < src.length() && pat.lastIndexOf(src.charAt(end + 1)) != -1) {
//例:
//src:shangyang
//pat:yang
// yang
//第一次s与y不匹配,g在yang的索引是3,yang应该偏移1位= 4-3(即模式串长度-g在源串中的最后出现的一个位置)
start = start + pat.length() - pat.lastIndexOf(src.charAt(end + 1));
} else {
start = start + pat.length() + 1;
}
end = start + pat.length() - 1;
}
return -1;
}