題意:
給你兩個字符串,判斷一個串的前綴是否是另一個串的後綴,求長度最長的滿足條件的串。
解題思路:
利用字符串hash可求
注意:
無
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <vector>
#include <math.h>
#include <string>
#include <set>
using namespace std;
#define MAXN 55000
//#define MOD 507
char s1[MAXN],s2[MAXN];
//set<string>st;
//typedef struct node{
// string s;
// node(){
//
// }
// node(char *key){
// //strcpy(s,key);
// s = key;
// }
//};
//vector<node>vt[MOD];
//void BKDRHash(char *str)
//{
// char *p = str;
//// unsigned int seed = 31; // 31 131 1313 13131 131313 etc..
//// unsigned int hash = 0,tmp;
//// int cnt = 0;
// char cc;
// while (*str)
// {
//// hash = hash * seed + (*str++);
//// tmp = hash;
//// tmp &= 0x7FFFFFFF;
//// tmp%=MOD;
// str++;
// cc = (*(str));
// *(str) = 0;
// // vt[tmp].push_back(node(p));
// st.insert(p);
// *(str) = cc;
//
// }
// //return (hash & 0x7FFFFFFF);
//}
int getans(char *str){
int len = (int)strlen(s2);
char * p = s2+len - 1;
char * p1 = str;
int cnt = 0;
int ans = 0;
char cc ;
unsigned int seed = 31; // 31 131 1313 13131 131313 etc..
unsigned int hash1 = 0,hash2 = 0,tmp0,tmp1,tmp2=1;
while((*str)&&cnt<len){
hash1 = hash1+(*p)*tmp2;
tmp1 = hash1;
tmp1 &=0x7FFFFFFF;
// tmp%=MOD;
// if(st.count(p)){
// ans = cnt+1;
// }
//tmp2*=seed;
//str++;
hash2 = hash2 * seed + (*str++);
tmp0 = hash2;
tmp0 &=0x7FFFFFFF;
if(tmp1==tmp0){
ans=cnt+1;
}
--p;
cnt++;
tmp2*=seed;
}
return ans;
}
void solve(){
//char *p = s1;
//int l = 1;
// BKDRHash(s1);
int ans = getans(s1);
if(!ans){
printf("%d\n",ans);
return ;
}
char *p = s1;
*(p+ans)= 0;
printf("%s %d\n",p,ans);
}
void clear(){
// for(int i=0;i<MOD;++i){
// if(vt[i].size()){
// vt[i].clear();
// }
// }
// if(st.size()){
// st.clear();
// }
}
int main(){
// for(int i=5000;;i++){
// bool flag = true;
// for(int j=2;j<=sqrt(i*1.0);j++){
// if(i%j==0){
// flag = false;
// break;
// }
// }
// if(flag){
// printf("%d\n",i);
// break;
// }
// }
// int flag1=0;
while(scanf("%s",s1)!=EOF){
scanf("%s",s2);
solve();
clear();
}
return 0;
}