1
0
Fork 0

Create prefix-hash.cc

This commit is contained in:
Ariel 2024-02-11 12:36:03 +08:00 committed by GitHub
parent da03e2446e
commit 34a0fcd040
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 43 additions and 0 deletions

43
string/prefix-hash.cc Normal file
View File

@ -0,0 +1,43 @@
class Solution {
public:
int countMatchingSubarrays(vector<int>& nums, vector<int>& pattern) {
constexpr int b = 31;
int n = nums.size(), m = pattern.size();
ll hp1 = 0, hp2 = 0;
ll pow1 = 1, pow2 = 1;
for (int i = 1; i <= m; ++i) {
hp1 = mod(hp1 + mod(pow1 * (pattern[i-1] + 1), MDL1), MDL1);
hp2 = mod(hp2 + mod(pow2 * (pattern[i-1] + 1), MDL2), MDL2);
pow1 = mod(pow1 * b, MDL1);
pow2 = mod(pow2 * b, MDL2);
}
vector<ll> hn1(n + 1), hn2(n + 1);
pow1 = 1, pow2 = 1;
for (int i = 2; i <= n; ++i) {
int p;
if (nums[i-1] > nums[i-2]) p = 1;
else if (nums[i-1] == nums[i-2]) p = 0;
else p = -1;
hn1[i] = mod(hn1[i-1] + mod(pow1 * (p + 1), MDL1), MDL1);
hn2[i] = mod(hn2[i-1] + mod(pow2 * (p + 1), MDL2), MDL2);
pow1 = mod(pow1 * b, MDL1);
pow2 = mod(pow2 * b, MDL2);
}
int res = 0;
pow1 = 1, pow2 = 1;
for (int i = 1; i + m <= n; ++i) {
if (mod(hp1 * pow1, MDL1) == mod(hn1[i+m] - hn1[i], MDL1) &&
mod(hp2 * pow2, MDL2) == mod(hn2[i+m] - hn2[i], MDL2)) {
res += 1;
}
pow1 = mod(pow1 * b, MDL1);
pow2 = mod(pow2 * b, MDL2);
}
return res;
}
};
subcrip
https://leetcode.cn/problems/number-of-subarrays-that-match-a-pattern-ii/solutions/2637701/zi-fu-chuan-ha-xi-by-subcrip-r3z4/
LeetCode