Skip to content

Commit aa78139

Browse files
authored
Create check-if-a-string-contains-all-binary-codes-of-size-k.cpp
1 parent ca51df0 commit aa78139

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Time: O(n * k)
2+
// Space: O(2^k)
3+
4+
class Solution {
5+
public:
6+
bool hasAllCodes(string s, int k) {
7+
unordered_set<int> lookup;
8+
const int base = 1 << k;
9+
if (base > s.length()) {
10+
return false;
11+
}
12+
int num = 0;
13+
for (int i = 0; i < s.length(); ++i) {
14+
num = (num << 1) + (s[i] - '0');
15+
if (i >= k - 1) {
16+
lookup.emplace(num);
17+
num -= (s[i - k + 1] - '0') * (base >> 1);
18+
}
19+
}
20+
return lookup.size() == base;
21+
}
22+
};
23+
24+
// Time: O(n * k)
25+
// Space: O(k * 2^k)
26+
class Solution2 {
27+
public:
28+
bool hasAllCodes(string s, int k) {
29+
unordered_set<string> lookup;
30+
const int base = 1 << k;
31+
if (base > s.length()) {
32+
return false;
33+
}
34+
for (int i = 0; i + k - 1 < s.length(); ++i) {
35+
lookup.emplace(s.substr(i, k));
36+
}
37+
return lookup.size() == base;
38+
}
39+
};

0 commit comments

Comments
 (0)