在做题的始终是在想将所有的输出结果保存了然后最后一次性输出,结果始终输出不了。现在就直接将输出改为cout输出了。现在虽然本地可以AC了,但是就想问问大佬们,我对多case的处理是否正确。
#include<iostream>
#include<string>
#include<vector>

using namespace std;

bool isMatch(const string &dict, const string &example);
vector<int> getNext(const string &needle, int m, vector<int> next);

int main()
{
	while (cin)		//此处是否正确?
	{
		int N;
		cin >> N;
		vector<string> dict(N, "");
		for (int i = 0;i<N;i++)
		{
			cin >> dict[i];
		}

		int M;
		cin >> M;
		vector<string> example(M, "");
		for (int i = 0;i<M;i++)
		{
			cin >> example[i];
		}

		for (int i = 0;i<M;i++)
		{
			int count = 0;
			for (int j = 0;j<N;j++)
			{
				if (isMatch(dict[j], example[i]))
				{
					count++;
				}
			}
			cout << count << endl;		//输出
		}
	}
	return 0;
}

//KMP匹配算法
bool isMatch(const string &dict, const string &example)
{
	int n = dict.size(), i = 0;
	int m = example.size(), j = 0;

	if (m>n) return false;
	if (n == 0 || m == 0)  return true;

	vector<int> next(m);
	next = getNext(example, m, next);

	while (j<m&&i<n)
	{
		if ((0>j) || dict[i] == example[j])
		{
			i++;
			j++;
		}
		else
		{
			j = next[j];
		}
	}
	return j == m ? true : false;
}

vector<int> getNext(const string &needle, int m, vector<int> next)
{
	int t = -1;
	next[0] = -1;
	int j = 0;
	while (j<m - 1)
	{
		if (0>t || needle[j] == needle[t])
		{
			j++;
			t++;
			next[j] = (needle[j] != needle[t] ? t : next[t]);
		}
		else
			t = next[t];
	}
	return next;
}