Hash——字符串匹配(求s1在s2中出现的次数)
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> using namespace std; typedef unsigned long long ull; ull base=131; ull po[100010],hs[100010*100]; char s1[100010],s2[100010*100]; int n,ans=1,T; //Hash处理(l,r)的字符串的hash值 ull geth(int l,int r) { return (ull)hs[r]-po[r-l+1]*hs[l-1]; } main() { // freopen("oulipo.in","r",stdin); // freopen("oulipo.out","w",stdout); po[0]=1; //预处理hash值 for (int i=1; i<=10010-5; i++) po[i]=po[i-1]*base , cout << po[i] << endl; scanf("%d",&T); while(T--) { scanf("%s%s",s1+1,s2+1); int l1=strlen(s1+1),l2=strlen(s2+1); ull a1=0,ans=0; for (int i=1; i<=l1; i++) a1=a1*base+(ull)s1[i]; for (int i=1; i<=l2; i++) hs[i]=hs[i-1]*base+s2[i]; for (int i=1; i+l1-1<=l2; i++) //截取相同长度,hash求值 if (a1==geth(i,i+l1-1)) ans++; printf("%d\n",ans); } }
用unique
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; typedef unsigned long long ull; ull base = 131; ull H[30010]; char s[1005]; int n, ans = 1; ull hashs(char s[]) { int len = strlen(s); ull ans = 0; for (int i = 0; i<len; i++) ans = ans*base + (ull)s[i]; return ans & 0x7fffffff; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%s", s); H[i] = hashs(s); } sort(H + 1, H + n + 1); printf("%d\n", (int)(unique(H + 1, H + n + 1) - H - 1)); return 0; }
、