add: 220531 [cpp]

This commit is contained in:
Eat-Swap 2022-05-31 09:27:17 +08:00
parent 24257a63a8
commit 773bd55e31
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 34 additions and 1 deletions

33
cpp/2205/220531.cpp Normal file
View File

@ -0,0 +1,33 @@
#include <string>
#include <bitset>
/**
* 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.
*/
class Solution {
public:
static bool hasAllCodes(const std::string& s, int k) {
if (s.length() <= k)
return false;
int cur = 0, cnt = 1, mask = (1 << k) - 1;
for (int i = 0; i < k; ++i)
cur = (cur << 1) | (s[i] & 1);
std::bitset<1 << 20> v;
v.set(cur);
for (int r = k; r < s.length(); ++r) {
cur = ((cur << 1) | (s[r] & 1)) & mask;
if (!v.test(cur)) {
v.set(cur);
++cnt;
}
}
return cnt == (1 << k);
}
};
int main() {
Solution::hasAllCodes("01", 1);
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2205)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2205 220531-CN.cpp)
ADD_EXECUTABLE(2205 220531.cpp)