常用字符串匹配算法

1)暴力法O(m+n)

2)KMP、Boyer_Mooer、Rabin_Rarp

 

暴力法

int strStr(String haystack, String needle){
    if ( needle.empty() ) return 0;
    if ( haystack.size() < needle.size() ) return -1;

    int n = haystack.size();
    int m = needle.size();

    for( int i=0; i<n-m; i++) {
        if( haystack[i] != needle[0] ) {
            continue;
        }
    
        for( int j=1; j<m; j++ ) {
            if(haystack[i+j] != needle[j] )
                break;    
        }

        if( j == m) return i;
    } 

    return -1;
}

 

KMP算法

//前缀计算函数
void computer_prefix( const char *pattern, int next[] ) {

    int i, j=-1;
    const int m = strlen(pattern);
    
    next[0]= j;
    
    for( i=1; i<m; i++ ) {
        while( j>-1 && pattern[j+1] != pattern[i] )
            j = next[j];
        
        if ( pattern[j+1] == pattern[i] )
            j = j+1;

        next[i] = j;
    }
} 


int kmp_matcher( const char *text, const char *pattern ) {
    
    int i, j=-1;
    const int n = strlen(text);
    const int m = strlen(pattern);
    
    if(m == 0) return 0;
    if(n < m) return -1;

    int *next = (int *)malloc(sizeof(int) *m);//需要判定是否分配成功
    computer_prefix(pattern, next);
    
    for( i=0; i<=n-m; i++) {
        while( j>-1 && pattern[j+1] != text[i] )
            j = next[j];

        if( text[i] == pattern[j+1] ) j++;
        
        if( j== m-1) {
            free(next);
            return i-j;
        }
    }

    free(next);
    return -1;
    
}
posted @ 2016-04-27 21:08  唐稚骅  阅读(372)  评论(0编辑  收藏  举报