KMP 寻找子串

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1010;
int next[maxn];
int l1=15,l2=3;//两串长度 
char str1[maxn]="abcaccdeacdaacd",str2[maxn]="acd";
int sum;
void get_next()
{//next数组保存了以i结尾的字符串的最长公共前缀和后缀的起始坐标
    int i,j;
    next[0] = j = -1;
    i = 0;
    while(i < l2)
    {
        while(j!=-1&&str2[j]!=str2[i])//自身和自身进行匹配
            j = next[j];
        next[++i] = ++j; 
    }
}
int kmp1()//找出现位置 
{
    int i,j;
    i = j = 0;
    while(i < l1&&j<l2)
    {
        while(j!=-1&&str1[i]!=str2[j])
        {
            j = next[j];
        }
        i++;
        j++;

    }
    if(j == l2)
        return i-j;//完全匹配时的开始下标,下标从0开始
    return -1;//不存在匹配情况 
}
int kmp2()//找出现次数 
{
    int i,j;
    i = j = 0;
    while(i < l1)//注意和返回下标的区别
    {
        while(j!=-1&&str1[i]!=str2[j])
        {
            j = next[j];
        }
        if(j == l2-1)
        {
           sum ++;
           j = next[j];
        }
        i++;
        j++;
    }
    return sum;//返回匹配次数 
}

int main()
{
	get_next();
	int ans1=kmp1();
	int ans2=kmp2(); 
	cout<<ans1<<" "<<ans2<<endl;
}

输出

8 2

猜你喜欢

转载自blog.csdn.net/aaakkk_1996/article/details/82192892
今日推荐