字符串匹配 sunday算法

#include"iostream"
#include"string.h"
using namespace std;

//BF算法
int strfind(char *s1,char *s2,int pos){
    int len1 = strlen(s1);
    int len2 = strlen(s2);
    int i = pos - 1,j = 0;
    while(j < len2){
        if(s1[i + j] == s2[j]){
            j++;
        }
        else{
            i++;
            j = 0;
        }
    }
    if(j == len2){
        return i + 1;
    }
    else{
        return 0;
    }
}

//sunday算法
int strsun(char *s1,char *s2,int pos){
    int len1 = strlen(s1);
    int len2 = strlen(s2);
    int shift[256],i,j;
    //shift表的初始化
    for(i = 0;i < 256;i++){
        shift[i] = len2 + 1;
    } 
    for(i = 0;i < len2;i++){
        shift[s2[i]] = len2 - i;
    }
    //遍历寻找
    i = pos - 1,j = 0;
    while(j < len2){
        if(s1[i + j] == s2[j]){
            j++;
        }
        else{
            i += shift[s1[i + len2]];    //不匹配就查表移动次数
            j = 0;
        }
    }
    if(j == len2){
        return i + 1;
    }
    else{
        return 0;
    }
}
int main(){
    char str1[] = "161234453218746321123456345567894";
    char str2[] = "123456";
    int n = 5;
    cout<<strfind(str1,str2,n)<<endl;
    cout<<strsun(str1,str2,n)<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/oleolema/p/9048337.html