Skip to content

Commit cb69ae1

Browse files
authored
Create number-of-subarrays-that-match-a-pattern-ii.cpp
1 parent 08100b6 commit cb69ae1

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Time: O(n)
2+
// Space: O(m)
3+
4+
// kmp
5+
class Solution {
6+
public:
7+
int countMatchingSubarrays(vector<int>& nums, vector<int>& pattern) {
8+
const auto& KMP = [](const auto& text, const auto& pattern) {
9+
const auto& getPrefix = [](const auto& pattern) {
10+
vector<int> prefix(size(pattern), -1);
11+
int j = -1;
12+
for (int i = 1; i < size(pattern); ++i) {
13+
while (j != -1 && pattern[j + 1] != pattern[i]) {
14+
j = prefix[j];
15+
}
16+
if (pattern[j + 1] == pattern[i]) {
17+
++j;
18+
}
19+
prefix[i] = j;
20+
}
21+
return prefix;
22+
};
23+
24+
int result = 0;
25+
const vector<int> prefix = getPrefix(pattern);
26+
int j = -1;
27+
for (int i = 0; i < size(text); ++i) {
28+
while (j > -1 && pattern[j + 1] != text[i]) {
29+
j = prefix[j];
30+
}
31+
if (pattern[j + 1] == text[i]) {
32+
++j;
33+
}
34+
if (j == size(pattern) - 1) {
35+
++result;
36+
j = prefix[j];
37+
}
38+
}
39+
return result;
40+
};
41+
42+
for (int i = 0; i + 1 < size(nums); ++i) {
43+
if (nums[i + 1] > nums[i]) {
44+
nums[i] = 1;
45+
} else if (nums[i + 1] < nums[i]) {
46+
nums[i] = -1;
47+
} else {
48+
nums[i] = 0;
49+
}
50+
}
51+
return KMP(nums, pattern);
52+
}
53+
};

0 commit comments

Comments
 (0)