数据结构——模式匹配

概念——字符串
子串:串中任意个连续的字符组成的子序列
主串:包含子串的串


主串S: a b a b c a b c a c b a b
模式串T: a b c a c


模式匹配——BF算法
从头开始模式串对主串进行暴力比对

int BF(char S[ ], char T[ ])
{
     i=0; j=0;   
    while (i<S.Length()&&j<T.length())
    {
         if (S[i]==T[j]) {
             i++;   j++;
         }  
         else {
             i=i-j+1;    j=0;
         }   
     }
     if (j>=T.length())  return (i-j);   
     else return -1;
}

模式匹配——KMP算法
BF算法时间性能低,每次查询大量回溯,没有利用已经匹配的结果。

bool kmp()
{
    //int ans = 0;
    get(s2);
    int i=0,j=0;
    while(i<s1.length()&&j<s2.length())
    {
        if(s1[i]==s2[j]) {
            i++,j++;
        }else if(next[j]==0) {
            i++,j++;
        }else {
            j=next[j];
        }
        if(j==s2.length()) {
                return true;
                break;
            //ans++;
            //j = 0;
        }
    }
    return false;
}

next数组的求解

void get(string s)
{
    next[0]=0;
    next[1]=1;
    int cn=0;
    int i=2;
    while(i<s.length())
    {
        if(s[i-1]==s[cn])
            next[i++]=++cn;
        else if(cn>0)
            cn=next[cn];
        else
            next[i++]=0;
    }
}

kmp例题
1、hdu 2087 剪花布条(kmp)

发布了247 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43658924/article/details/102467798