【SOJ-2652,2307-KMP】计算模式串在源串中的出现次数

源代码如下:

char T[1000005];
char P[10005];
int next[10005];
void Get_Next(char *P)
{
	int TLength = strlen(P);
    next[0] = -1;
    int i = 0, j = -1;
	while (i < TLength) {
        if (j == -1 || P[i] == P[j]) {
            ++i;
            ++j;
            next[i] = j;
        } else j = next[j];
    }
}
int ans;
void KMP_Matcher(char *T,char *P)
{
    int PLength = strlen(P);
    int TLength = strlen(T);
    int i, j = 0;
    for (i = 0; i < TLength; ) {
		while (i < TLength && j < PLength) {
			if (j == -1 || T[i] == P[j]) {
                ++i;
                ++j;
            } else j = next[j];
        }
        if (j == PLength) {
            ++ans;
            j = next[j];
        }
    }
    printf("%d\n",ans);
}
int main()
{
    int n;
    scanf("%d", &n);
    getchar();
    while (n--) {
        ans = 0;
        gets(P);
        gets(T);
        Get_Next(P);
        KMP_Matcher(T, P);
    }
    return 0;
}

另附:游洪跃老师的数据结构书代码(求出模式串在源串中的出现位置)

char T[1000005];
char P[10005];
int next[10005];
void Get_Next(char *P)
{
	int TLength = strlen(P);
    next[0] = -1;
    int i = 0, j = -1;
	while (i < TLength) {
        if (j == -1 || P[i] == P[j]) {
            ++i;
            ++j;
            next[i] = j;
        } else j = next[j];
    }
}
int KMP_Matcher(char *T,char *P, int pos)
{
    int PLength = strlen(P);
    int TLength = strlen(T);
    int i = pos, j = 0;
    while (i < TLength && j < PLength) {
		if (j == -1 || T[i] == P[j]) {
			++i;
			++j;
		} else j = next[j];
	}
	if (j < PLength) return -1;
	else return i - j;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值