面试路之常用字符串匹配算法(2)

1)暴力法O(m+n)

2)KMP、Boyer_Mooer、Rabin_Rarp

 

暴力法

《面试路之常用字符串匹配算法(2)》

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;
}

《面试路之常用字符串匹配算法(2)》

 

KMP算法

《面试路之常用字符串匹配算法(2)》

//前缀计算函数
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;
    
}

《面试路之常用字符串匹配算法(2)》

    原文作者:唐稚骅
    原文地址: https://blog.csdn.net/tangchenchan/article/details/51265089
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞