Given two strings A and B, your task is to find a substring of A called justice string, which has the same length as B, and only has at most two characters different from B.
Input
The first line of the input contains a single integer T, which is the number of test cases.
For each test case, the first line is string A, and the second is string B.
Both string A and B contain lowercase English letters from a to z only. And the length of these two strings is between 1 and 100000, inclusive.
Output
For each case, first output the case number as “Case #x: “, and x is the case number. Then output a number indicating the start position of substring C in A, position is counted from 0. If there is no such substring C, output -1.
And if there are multiple solutions, output the smallest one.
Sample Input
3
aaabcd
abee
aaaaaa
aaaaa
aaaaaa
aabbb
Sample Output
Case #1: 2
Case #2: 0
Case #3: -1
分析: 枚举A的起点,然后求子串s和B的LCP,看能否跳过最多2个字符,匹配成功。
代码
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define ULL unsigned long long
const int N = (int)2e5+11;
const int M = (int)1e6+11;
const int mod = (int)1e9+7;
const int seed = (int) 233;
const int inf = 0x3f3f3f3f;
ULL H[N*2],X[N*2];
void init(char *s){
int len=strlen(s);
H[len]=0;
for(int i=len-1;i>=0;i--){
H[i]=H[i+1]*seed+s[i]-'a';
}
X[0]=1;
for(int i=1;i<=len;i++){
X[i]=X[i-1]*seed;
}
}
char A[N*2],B[N];
inline ULL getHash(int a,int mid){
return H[a]-H[a+mid]*X[mid];
}
int lena,lenb;int L ;
int LCP(int a,int b){ // log的时间求出 LCP
int le=1,ri=L-b;
int ans=0;
while(le<=ri){
int mid=(le+ri)>>1;
if(getHash(a,mid) == getHash(b,mid)) {
ans=max(ans,mid);
le=mid+1;
}else ri=mid-1;
}
return ans;
}
int main(){
int t; scanf("%d",&t); int cas=1;
while(t--){
scanf("%s%s",&A,&B);
lena=strlen(A); lenb=strlen(B); L=lena+lenb;
strcat(A,B);
init(A);
int ans=-1;
for(int i=0;i<lena-lenb+1;i++){
int l1=LCP(i,lena);
if(l1==lenb) {ans=i; break;}
l1++;
int l2=LCP(i+l1,lena+l1);
if(l2+l1==lenb) {ans=i; break;}
l2++;
int l3=LCP(i+l1+l2,lena+l1+l2);
if(l1+l2+l3==lenb) {ans=i; break;}
}
printf("Case #%d: %d\n",cas++,ans);
}
return 0;
}