参考文章:
http://blog.csdn.net/lin_bei/archive/2006/09/20/1252686.aspx
1.强力匹配,效率低:
#include <stdio.h>
#include <string.h>
void naive_string_matcher(char *str, char *childstr, int *position)
{
int plen, clen, i = 0, j = 0;
plen = strlen(str);
clen = strlen(childstr);
for(i = 0; i < plen; i++){
if(str[i] == childstr[0]){
j = 0;
while(str[i+j] == childstr[j]){
j++;
}
if(j == clen){
*position = i;
break;
}
}
}
}
int main(int argc, char **argv)
{
char parent[100] = "ababcabcacbab";
char child[100] = "abcac";
int pos = 0;
naive_string_matcher(parent, child, &pos);
printf("first matcher position #%d\n", pos);
return 0;
}
|
2.kmp算法,时间复杂度O(n):
#include <stdio.h>
#include <string.h>
int next[20];
void get_nextval(char *t, int next[])
{
int j = 0, k = -1;
next[0] = -1;
while(t[j] != '\0'){
if(k == -1 || t[j] == t[k]){
k++;
j++;
if(t[j] != t[k]){
next[j] = k;
}
else{
next[j] = next[k];
}
}
else{
k = next[k];
}
}
}
int index_kmp(char *text, char *pattern)
{
int len = strlen(pattern);
int i = 0, j = 0, index = 0;
while(text[i] != '\0' && pattern[j] != '\0'){
if(text[i] == pattern[j]){
i++;
j++;
}
else{
index += j - next[j];
if(next[j] != -1){//next[i]>=0
j = next[j];
}
else{//nexr[i] == -1
j = 0;
i++;
}
}
}
if(pattern[j] == '\0'){
return index;
}
else{
return -1;
}
}
int main(int argc, char **argv)
{
char parent[100] = "ababcabcacbab";
char child[20] = "bcab";
get_nextval(child, next);
printf("%d\n", index_kmp(parent, child));
return 0;
}
|
阅读(1097) | 评论(0) | 转发(0) |