公共子串 字符串哈希
生活随笔
收集整理的這篇文章主要介紹了
公共子串 字符串哈希
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
You are given two long strings?AA?and?BB. They are comprised of lowercase letters. You should compute how many suffixes of?AA?are the prefixes of?BB.
Input
In the first line is a number?TT?(0<T≤1000<T≤100) , indicating the cases following. In the next T lines each line contains two strings —?AA?and?BB. (?0<|A|≤105,0<|B|≤1050<|A|≤105,0<|B|≤105)
Output
There should be exactly?TT?lines. Each line contain a number — the answer.
Sample Input
1 abcc ccbaSample Output
2HINT
In the first case, cc and c are two of the suffixes of string A, and they are the prefixes of string B.
題意:問給你兩個字符串A和B,其中A的后綴也是B的前綴的子串有多少個。
題解:很簡單的字符串hash問題,
設i是從 0 循環到min(lenA,lenB)
hasha += Base^n * A[lenA-1-i];
hashb = hashb * Base + B[i];
然后判斷hasha == hashb 那么cnt++
代碼:
#include <cstdio> #include <iostream> #include <cstring> #include <algorithm> using namespace std; typedef unsigned long long ull; const ull Base = 100000007; const ull MAX = 1e5+5; char A[MAX],B[MAX]; int main() {int T;scanf("%lld",&T);while(T--){scanf("%s %s",A,B);ull lenA = strlen(A),ull asum = 0;ull lenB = strlen(B),ull bsum = 0;ull t = 1;int ans = 0;for(int i = 0;i < min(lenA,lenB);i++){asum += t*A[lenA-1-i];bsum = bsum * Base + B[i];t *= Base;if(asum == bsum) ans++;}cout<<ans<<endl;}return 0; }
總結
以上是生活随笔為你收集整理的公共子串 字符串哈希的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网上冲浪是什么 网上冲浪的解释
- 下一篇: 数学题 贪心+二分答案