站外题求助
  • 板块学术版
  • 楼主qfpjm
  • 当前回复5
  • 已保存回复5
  • 发布时间2021/8/23 09:11
  • 上次更新2023/11/4 09:24:21
查看原帖
站外题求助
342868
qfpjm楼主2021/8/23 09:11
给你两个串A,B,每次在B串中从左到右找串A,并将该子串删除,直到找不到为止,问你能删几次。

我的代码为什么死循环了

#include <bits/stdc++.h>

using namespace std;

char s1[1000005], s2[1000005];
int len1, len2, next[1000005], ans;

void getnext()
{
	int j = 0;
	for (int i = 2 ; i <= len2 ; i ++)
	{
		while (j && s2[i] != s2[j + 1])
		{
			j = next[j];
		}
		if (s2[j + 1] == s2[i])
		{
			j ++;
		}
		next[i] = j;
	}
}

void KMP()
{
	while (len1 >= len2)
	{
		memset(next, 0, sizeof(next));
		getnext(); 
		int j = 0;
		for (int i = 1 ; i <= len1 ; i ++)
		{
			while (j && s2[j + 1] != s1[i])
			{
				j = next[j];
			}
			if (s2[j + 1] == s1[i])
			{
				j ++;
			}
			if (j == len2) 
			{
				char ch[100005];
				int len3;
				ans ++;
				for (int j = 1 ; j <= len1 ; j ++)
				{
					if (j >= i - len2 + 1 && j <= i)
					{
						continue;
					}
					ch[++ len3] = s1[j];
				}
				len1 -= len2;
				for (int j = 1 ; j <= len1 ; j ++)
				{
					s1[j] = ch[j];
				}
				j = next[j];
				break;
			}
		}
	}
}

int main()
{
	cin >> s2 + 1 >> s1 + 1;
	len1 = strlen(s1 + 1);
    len2 = strlen(s2 + 1);
	KMP();
	cout << ans;
	return 0;
}
2021/8/23 09:11
加载中...