zoukankan      html  css  js  c++  java
  • poj3461

    kmp算法

    首先,这类题不要用cin,应该用scanf和char[]

    其次,overlap是重叠的意思,不是扣圈的意思

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cstdlib>
    using namespace std;
    
    const int maxm = 1000005, maxn = 10005;
    
    char str[maxm + maxn], pat[maxn];
    int len, len1, len2;
    
    int kmp()
    {
    	int fail[maxn];
    	int i, j, k;
    	memset(fail, -1, sizeof(fail));
    	for (i = 1; i < len2; ++i)
    	{
    		for (k = fail[i - 1]; k >= 0 && pat[i] != pat[k + 1]; k = fail[k])
    			;
    		if (pat[k + 1] == pat[i])
    			fail[i] = k + 1;
    	}
    	i = j = 0;
    	int ans = 0;
    	while (i < len)
    	{
    		if (pat[j] == str[i])
    			++i, ++j;
    		else if (j == 0)
    			++i;
    		else
    		{
    			if (j == len2)
    				ans++;
    			j = fail[j - 1] + 1;
    		}
    	}
    	if (j == len2)
    		ans++;
    	return ans;
    }
    
    int main()
    {
    	//freopen("D:\\t.txt", "r", stdin);
    	int t;
    	scanf("%d", &t);
    	while (t--)
    	{
    		scanf("%s", pat);
    		scanf("%s", str);
    		len1 =strlen(str);
    		len2 =strlen(pat);
    		len = len1;
    		printf("%d\n", kmp());
    	}
    	return 0;
    }
    
    
  • 相关阅读:
    栈和队列
    数组的遍历查找
    字符串的子串
    两个字符串
    字符串的遍历
    字符串的替换
    数组和矩阵
    Django 自带的ORM增删改查
    what's the CRSF ??
    Rabbitmq -Publish_Subscribe模式- python编码实现
  • 原文地址:https://www.cnblogs.com/rainydays/p/1948632.html
Copyright © 2011-2022 走看看