Last active
December 22, 2020 13:22
-
-
Save stoensin/fcde1171615b7ad0bf1f7697bf8f3ee6 to your computer and use it in GitHub Desktop.
Sunday算法其实思想跟BM算法很相似,只不过Sunday算法是从前往后匹配,在匹配失败时关注的是文本串中参加匹配的最末位字符的下一位字符。如果该字符没有在匹配串中出现则直接跳过,即移动步长= 匹配串长度+ 1;否则,同BM算法一样其移动步长=匹配串中最右端的该字符到末尾的距离+1。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
int getIndex(char *tp, char ch) { | |
if (tp == NULL || !ch) | |
return -1; | |
int tp_len = strlen(tp); | |
for (int i = 0; i < tp_len; i++) { | |
if (ch == tp[i]) { | |
return tp_len - i - 1; | |
} | |
} | |
return -1; | |
} | |
int sunday(char *source, char *target) { | |
int m = strlen(source); | |
int n = strlen(target); | |
int i = 0, j = 0; | |
int last = 0; | |
while (i < m) { | |
if (source[i] == target[j]) { | |
printf("match %c;\n", source[i]); | |
if (j == n - 1) | |
return 1; | |
i++; | |
j++; | |
} else { | |
last = n + i - j; | |
int offset_i = getIndex(target, source[last]); | |
if (offset_i == -1) { | |
i = last + 1; | |
j = 0; | |
} else { | |
i = offset_i + 1; | |
j = 0; | |
} | |
} | |
} | |
puts("match faild!"); | |
return 0; | |
} | |
int main(void) { | |
char *c1 = "Hello,world!"; | |
char *c2 = "wo"; | |
sunday(c1, c2); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment