[LeetCode] Check If a String Contains All Binary Codes of Size K

1461. Check If a String Contains All Binary Codes of Size K

Given a binary string s and an integer k.

Return True if every binary code of length k is a substring of s. Otherwise, return False.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool hasAllCodes(string s, int k) {
int binary = 0;
int bitwiseAND = (1<<k) - 1;
for(int i = 0; i < k; binary = ((binary << 1) | (s[i++] & 0b1111)));
unordered_set<int> binarySet {binary};
for(int i = k; i <= s.length(); binary = ((binary<<1) & bitwiseAND) | (s[i++] & 0b1111)) {
binarySet.insert(binary);
}

return binarySet.size() == bitwiseAND + 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/12/PS/LeetCode/check-if-a-string-contains-all-binary-codes-of-size-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.