zoukankan      html  css  js  c++  java
  • 字符串匹配 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;
    }
  • 相关阅读:
    20180315 代码错题(7)
    20180315 代码错题(6)
    20180315 代码错题(5)
    20180315 代码错题(4)
    01背包问题(动态规划)
    等差素数列 暴力搜索
    小L记单词
    三角形
    小L的试卷
    小L的项链切割 (回文串)
  • 原文地址:https://www.cnblogs.com/oleolema/p/9048337.html
Copyright © 2011-2022 走看看