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

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) {
        if( haystack[i] != needle[0] ) {
            continue;
        }
    
        for( int j=1; 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 ) {
        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;
    
}
复制代码

你可能感兴趣的:(面试)