zoukankan      html  css  js  c++  java
  • 字符串匹配方法

    介绍两种字符串匹配方法

    1.暴力匹配

    母串用s表示,长度为m

    子串用p表示,长度为n

    时间复杂度为:(m-n+1)n

    算法:从s串的第一个字符开始匹配,若匹配,继续根据p向后匹配,若后续的不匹配,s右移重新匹配p 

    2.KMP算法

    母串用s表示,长度为m

    子串用p表示,长度为n

    时间复杂度为:预处理阶段m

    算法:①计算next[]数组 ②字符串匹配

    【参考】 

     http://kb.cnblogs.com/page/176818/

     http://www.cnblogs.com/gaochundong/p/string_matching.html

     http://blog.csdn.net/v_july_v/article/details/7041827 

    【C语言实现】 

     1.暴力匹配

    #include <stdio.h>
    #include <string.h>
    int main()
    {
    char *s="ASDFZGasdFZGdfasdFZGsdFZGFZG";
    char *p="FZG";
    int i=0,j=0,count=0;
    int len_s=strlen(s);
    int len_p=strlen(p);
    while(i<len_s&&j<len_p)
    {
    if (s[i]==p[j])
    {
    i++;
    j++;
    else
    {
    i=i-j+1;
    j=0;
    }
    if (len_p==j)
    { 

    printf("%d ",i-j);//打印匹配成功的起始位置 

    count++;//计算匹配次数 
    j=0;
    }
    }
    printf("%d ",count);//打印匹配次数
    return 0;
    }

     2.KMP算法 

    #include <stdio.h>
    #include <string.h>
    int KmpSearch(char* s, char* p, int next[]);
    void GetNext(char* p,int next[]);
    int main()
    {
    char *s="asfdafASDdfda";
    char *p="SD";
    int next[3]={0};
    GetNext(p,next);
    KmpSearch(s,p,next);
    return 0;
    }
    int KmpSearch(char* s, char* p, int next[])  
    {  
    int i = 0;  
    int j = 0;  
    int sLen = strlen(s);  
    int pLen = strlen(p);  
    while (i < sLen && j < pLen)  
    {  
    //①如果j = -1,或者当前字符匹配成功(即S[i] == P[j]),都令i++,j++      
    if (j == -1 || s[i] == p[j])  
    {  
    i++;  
    j++;  
    }  
    else  
    {  
    //②如果j != -1,且当前字符匹配失败(即S[i] != P[j]),则令 i 不变,j = next[j]      
    //next[j]即为j所对应的next值        
    j = next[j];  
    }  
    }  
    if (j == pLen)
    {
    printf("%d ",i-j);//打印匹配成功的起始位置 
    return i - j;  
    }
    else  
    return -1;  
    void GetNext(char* p,int next[])  //该函数为计算next[]数组,看不太懂。。。算法暂且先记住吧
    {  
    int pLen = strlen(p);  
    next[0] = -1;  //第一位数字置为-1,其余的是最长公共元素右移一位
    int k = -1;  
    int j = 0;  
    while (j < pLen - 1)  
    {  
    //p[k]表示前缀,p[j]表示后缀  
    if (k == -1 || p[j] == p[k])   
    {  
    ++k;  
    ++j;  
    next[j] = k;  
    }  
    else   
    {  
    k = next[k];  
    }  
    }  
    }
  • 相关阅读:
    170929-关于md5加密
    170911-关于maven的知识点
    opencv-python 学习初探1
    使用PDFminer3k解析pdf为文字遇到:WARING:root:GBK-EUC-H
    Python time strptime()与time strftime()
    chromedriver下载安装
    计数
    高效的几个小技巧
    phantomjs在win10下的安装
    win10下安装lxml
  • 原文地址:https://www.cnblogs.com/kinghero/p/5604415.html
Copyright © 2011-2022 走看看