1.Sunday算法是什么?
Sunday算法是Daniel M.Sunday于1990年提出的一种字符串模式匹配算法。其核心思想是:在匹配过程中,模式串并不被要求一定要按从左向右进行比较还是从右向左进行比较,它在发现不匹配时,算法能跳过尽可能多的字符以进行下一步的匹配,从而提高了匹配效率。
2.描述
Sunday算法的优点主要体现在以下2点:
1)当主串匹配至第3个元素失败时,如下图:
此时,模式串的P[2]=T[5],因此直接移动模式串,将i=5和j=2的元素进行比较。
移动的步长 = plength - j = 5 - 2 = 3;
2)若模式串中不包含字符’F’时,则移动模式串,将P[0]与T[6]进行比较。
移动的步长 = plength + 1 = 5 + 1 = 6;
3.Sunday算法实现
/*
* Sunday匹配
*/
char *Sunday(char *text, char *pattern) {
if (text == NULL) return NULL;
int tlength = strlen(text);
int plength = strlen(pattern);
int bad_shift[ASIZE];
// 对任意字符移动plength + 1长度
for (int i = 0; i < ASIZE; i++) bad_shift[i] = plength + 1;
for (int i = 0; i < plength; i++) bad_shift[pattern[i]] = plength - i;
int i = 0, j;
while (i < tlength) {
j = 0;
while (text[i++] == pattern[j++] && j < plength)
;
// 主串回归起始位置
i -= j;
if (j == plength) return text + i;
i += bad_shift[text[i + plength]];
}
return NULL;
}
4.接下来
除了以上的字符串匹配算法,还存在其它的算法。
例:有限自动机算法(Finite Automation)、 Simon 算法、Colussi 算法、Galil-Giancarlo 算法、Apostolico-Crochemore 算法等。
具体原理可以参照以下链接:
字符串匹配算法