Skip to content

Commit 3ecb1db

Browse files
authored
Create find-pattern-in-infinite-stream-ii.cpp
1 parent 4365231 commit 3ecb1db

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Time: O(p + n)
2+
// Space: O(p)
3+
4+
// kmp
5+
class Solution {
6+
public:
7+
int findPattern(InfiniteStream* stream, vector<int>& pattern) {
8+
const auto& getPrefix = [](const auto& pattern) {
9+
vector<int> prefix(size(pattern), -1);
10+
int j = -1;
11+
for (int i = 1; i < size(pattern); ++i) {
12+
while (j > -1 && pattern[j + 1] != pattern[i]) {
13+
j = prefix[j];
14+
}
15+
if (pattern[j + 1] == pattern[i]) {
16+
++j;
17+
}
18+
prefix[i] = j;
19+
}
20+
return prefix;
21+
};
22+
23+
vector<int> result;
24+
const vector<int> prefix = getPrefix(pattern);
25+
int j = -1;
26+
for (int i = 0; ; ++i) {
27+
const auto d = stream->next();
28+
while (j > -1 && pattern[j + 1] != d) {
29+
j = prefix[j];
30+
}
31+
if (pattern[j + 1] == d) {
32+
++j;
33+
}
34+
if (j == size(pattern) - 1) {
35+
return i - j;
36+
}
37+
}
38+
return -1;
39+
}
40+
};

0 commit comments

Comments
 (0)