【YBTOJ】移位包含

题目大意:

给定两个字符串 (s,t)(s) 可以旋转,问 (t) 是否可能成为 (s) 的子串。

正文:

(s) 复制一遍,找子串直接 KMP。

代码:

const int N = 110;

inline ll READ()
{
	ll x = 0, f = 1;
	char c = getchar();
	while (c != '-' && (c < '0' || c > '9')) c = getchar();
	if (c == '-') f = -f, c = getchar();
	while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0', c = getchar();
	return x * f;
}

string s, st; 
int nxt[N], n, m;

void INIT()
{
	int j = 0;
	for (int i = 1; i < m; i++)
	{
		while (j && st[i] != st[j]) j = nxt[j];
		if (st[i] == st[j]) j++;
		nxt[i + 1] = j;
	}
}

bool ans;

int main()
{
	cin >> s >> st;
	s = s + s;
	n = s.size(), m = st.size();
	INIT();
	int j = 0;
	for (int i = 0; i < n; i++)
	{
		while (j && s[i] != st[j]) j = nxt[j];
		if (s[i] == st[j]) j++;
		if (j == m)
		{
			ans = 1;
			break;
		}
	}
	if (ans) puts("true");
	else puts("false");
	return 0;
}
原文地址:https://www.cnblogs.com/GJY-JURUO/p/14717615.html