Justice String
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
Source
Tags ( Click to see )
被称做sb hash的题目。。
代码很短。就是每次从两个位置开始找公共前缀。 找到后,justice用一次,接着找。知道justice用完。。从第一个位置开始判断。 二分查找思想实现求公共前缀。。
#include <cstdio>
#include <cstdlib>
const int N = 111111;
#define LL long long
const long long MOD = 1e9+7;
const int SEED = 31;
LL base[N];
char s1[N],s2[N];
LL a[N],b[N];
int n1,n2;
int len;
void format(char s[],LL rec[],int &len){
LL ret = 0;
int i;
for(i = 1; s[i] ;i++){
ret = (ret * SEED + s[i]) % MOD;
rec[i] = ret;
}
len = i-1;
}
LL calc(LL F[],int l,int r){
return ((F[r]-F[l-1]*base[r-l+1])%MOD+MOD)%MOD;
}
int cl(int i,int j){
int ret = 0;
int l = 1,r = n2-j+1;
while(l <= r){
int mid = (l+r)>>1;
if(calc(a,i,i+mid-1) == calc(b,j,j+mid-1) ){
l = mid + 1;
ret = mid ;
}else r = mid-1;
}
return ret;
}
bool check(int start){
int use = 0;
int i,j=1;
for(i = start; i <= n1 && use < 2 && j < n2; i++,j++){
int logest = cl(i,j);
i += logest ;
j += logest ;
use++;
if(use >= 2 && j < n2){
logest = cl(i+1,j+1);
j += logest;
if(j >= n2)return true;
else return false;
}
}
return true;
}
int main(){
int t,tt=0;
scanf("%d",&t);
base[0] = 1;
for(int i = 1;i < N;i++){
base[i] = base[i-1] * SEED % MOD;
}
while(t--){
scanf("%s %s",s1+1,s2+1);
format(s1,a,n1);
format(s2,b,n2);
int ret = -1;
for(int i = 1;i <= n1 - n2 + 1;i++){
if(check(i)){
ret = i-1;
break;
}
}
printf("Case #%d: %d\n",++tt,ret);
}
return 0;
}