题目: You are given two long strings Aand B. They are comprised of lowercase letters. You should compute how many suffixes of Aare the prefixes of B. 要求为:A的后缀是B的前缀; 题目要求符合要求的子串的个数
题解: 将B串在前A串在后,两个串直接加一个其他字符之后连接起来成为字符串S。
利用next_数组的性质,next_[i]存储了S以0开头i结尾的子串中,以i结尾的后缀和该子串的前缀的最大匹配值,当该值不为0时,即为一个合法的答案,最后遍历next_数组统计一遍数字,减掉next_[n-1](把整个字符串当作既是前缀又是后缀)这个答案即可。
PS :尽量避免使用C++的各种关键字命名变量和函数,否则部分编译器会CE。
代码:
#include<stdio.h> #include<string.h> #include<string> #include<iostream> using namespace std; #define MAX 200005 int next_[200005]; char a[200005] , b[200005] ,s[200005]; int sum[200005]; void get_next(int len) { int i,j; memset(next_,0,sizeof(next_)); i=0; j=-1; next_[0]=-1; while(i<len) { if(j==-1||(j>=0&&s[i]==s[j])) { ++i; ++j; next_[i]=j; } else j=next_[j]; } } int main() { int len,i,k , t; scanf("%d" , &t) ; while(t--) { k = 0 ; memset(a,'\0',sizeof(a)); memset(b,'\0',sizeof(b)); memset(s,'\0',sizeof(s)); scanf("%s%s",a,b) ; strcat(s,b) ; strcat(s,"*"); strcat(s,a); //cout << s; len=strlen(s); get_next(len); i = len; while(i) { k++; i=next_[i]; } printf("%d\n",k-1); } return 0; }