The daily life of Niuniu and the string (find how many consecutive letters in the input characters overlap with the prefix of the given string at most)

topic

No key code will be wa

abcdefg
1
adcabcabcdefg

Well understood abc next traversed a non-compliance cnt = 0;
while traversing from next next start will start from abcddefg in b
and want to start from a need to reduce if j- j, then sank into the cycle of death
at this time We choose j-cnt, although it will traverse from the second letter of the string that has just been traversed (one more traversal), but it has a very good effect. Currently, there is no better way to solve this problem.

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
char a[111111];
int n;
char s[111111];
int ans;
int cnt;
int v[111111], t;//用v数组存所有的cnt结果
int maxs;//用 maxs更新最大的cnt
bool cmp(int a, int b)
{
    
    
	return a > b;
}
int main()
{
    
    
	scanf("%s", a);
	cin >> n;
	for(int i = 0; i < n; i++)
	{
    
    
		scanf("%s",s);
		cnt = 0;
		maxs = 0;
		memset(v, 0, sizeof(v));
		t = 0;
		for(int j = 0; j < strlen(s); j++)
		{
    
    
			cout << "j = " << j << "\n";
			if(a[cnt] == s[j]){
    
    
				cnt++;
				//cout << s[i] << "\n";
				v[t++] = cnt;
				maxs = max(maxs, cnt);
			}
			else{
    
    
				v[t++] = cnt;
				j = j - cnt;  //  关键  一直wa
				//cout << "j = " << j << "\n";
				cnt = 0;
			}
		}
		sort(v, v + t ,cmp);
		//printf("v = %d\n",v[0]);
		ans += v[0];// 或者 把v[0]改成maxs
	}
	
	cout << ans << "\n";
	return 0;
}

Guess you like

Origin blog.csdn.net/cosx_/article/details/109992722