M1461.检查一个字符串是否包含所有长度为 K 的二进制子串
bit manipulation, https://leetcode.cn/problems/check-if-a-string-contains-all-binary-codes-of-size-k/
思路:滑动窗口, 学会了 stoi (string to int) 的用法, int stoi( const std::string& str, std::size_t* pos = nullptr, int base = 10 )
cpp
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool hasAllCodes(string s, int k) {
int num = stoi(s.substr(0, k), nullptr, 2);
unordered_set<int> a;
a.insert(num);
for (int i = k; i < s.length(); i++) {
num <<= 1;
if (num >= (1 << k)) {
num -= (1 << k);
}
num += (s[i] - '0');
a.insert(num);
}
return a.size() == (1 << k);
}
};用时10min
cpp
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
class Solution
{
public:
bool hasAllCodes(string s, int k)
{
int total_needed = 1 << k;
if (s.size() < (size_t)total_needed + k - 1)
return false;
vector<bool> seen(total_needed, false);
int x = 0;
int cnt = 0;
int MASK = total_needed - 1;
for (int i = 0; i < k - 1; ++i)
{
x = (x << 1) | (s[i] & 1);
}
for (int i = k - 1; i < s.length(); ++i)
{
x = ((x << 1) & MASK) | (s[i] & 1);
if (!seen[x])
{
seen[x] = true;
if (++cnt == total_needed)
return true;
}
}
return false;
}
};
int main()
{
cin.tie(nullptr)->sync_with_stdio(false);
Solution sol;
string s = "0110";
int k = 2;
cout << sol.hasAllCodes(s, k) << '\n';
return 0;
}共用时20min
思路:直接提取
cpp
class Solution {
public:
bool hasAllCodes(string s, int k) {
const int n = s.length();
if(n - k + 1 < (1 << k)) return false;
vector<bool> buc;
buc.resize(1 << k);
int x = 0;
for(int i = 0; i < n; i++) {
x <<= 1;
x |= s[i] - '0';
x &= (1 << k) - 1;
if(i >= k - 1) buc[x] = true;
}
return ranges::count(buc, false) == 0;
}
};