Chinaunix首页 | 论坛 | 博客
  • 博客访问: 434658
  • 博文数量: 103
  • 博客积分: 5010
  • 博客等级: 大校
  • 技术积分: 971
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-11 17:22
文章分类
文章存档

2008年(77)

2007年(26)

我的朋友

分类: C/C++

2008-05-09 23:06:30

参考文章:
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) |
给主人留下些什么吧!~~