|
| 1 | + |
| 2 | +#include "leetcode/problems/check-if-a-string-contains-all-binary-codes-of-size-k.h" |
| 3 | + |
| 4 | +namespace leetcode { |
| 5 | +namespace problem_1461 { |
| 6 | + |
| 7 | +// 滑动窗口 + 位运算 + 哈希集合 |
| 8 | +// 时间复杂度: O(n), 空间复杂度: O(2^k) |
| 9 | +static bool solution1(string s, int k) { |
| 10 | + const int n = s.size(); |
| 11 | + const int total = 1 << k; // 2^k |
| 12 | + |
| 13 | + // 剪枝:字符串长度不足以包含所有子串 |
| 14 | + if (n < k + total - 1) { |
| 15 | + return false; |
| 16 | + } |
| 17 | + |
| 18 | + unordered_set<int> seen; |
| 19 | + int mask = total - 1; // k 个 1,用于取低 k 位 |
| 20 | + int num = 0; |
| 21 | + |
| 22 | + // 初始化窗口 |
| 23 | + for (int i = 0; i < k; ++i) { |
| 24 | + num = (num << 1) | (s[i] - '0'); |
| 25 | + } |
| 26 | + seen.insert(num); |
| 27 | + |
| 28 | + // 滑动窗口 |
| 29 | + for (int i = k; i < n; ++i) { |
| 30 | + // 去掉最高位,加入新位 |
| 31 | + num = ((num << 1) & mask) | (s[i] - '0'); |
| 32 | + seen.insert(num); |
| 33 | + // 提前退出:如果已经找到所有子串 |
| 34 | + if (seen.size() == total) { |
| 35 | + return true; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return seen.size() == total; |
| 40 | +} |
| 41 | + |
| 42 | +// 使用 vector<bool> 替代 unordered_set,空间更优 |
| 43 | +// 时间复杂度: O(n), 空间复杂度: O(2^k) |
| 44 | +static bool solution2(string s, int k) { |
| 45 | + const int n = s.size(); |
| 46 | + const int total = 1 << k; // 2^k |
| 47 | + |
| 48 | + // 剪枝 |
| 49 | + if (n < k + total - 1) { |
| 50 | + return false; |
| 51 | + } |
| 52 | + |
| 53 | + vector<bool> seen(total, false); |
| 54 | + int count = 0; |
| 55 | + int mask = total - 1; |
| 56 | + int num = 0; |
| 57 | + |
| 58 | + // 初始化窗口 |
| 59 | + for (int i = 0; i < k; ++i) { |
| 60 | + num = (num << 1) | (s[i] - '0'); |
| 61 | + } |
| 62 | + seen[num] = true; |
| 63 | + count = 1; |
| 64 | + |
| 65 | + // 滑动窗口 |
| 66 | + for (int i = k; i < n; ++i) { |
| 67 | + num = ((num << 1) & mask) | (s[i] - '0'); |
| 68 | + if (!seen[num]) { |
| 69 | + seen[num] = true; |
| 70 | + ++count; |
| 71 | + if (count == total) { |
| 72 | + return true; |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + return count == total; |
| 78 | +} |
| 79 | + |
| 80 | +CheckIfAStringContainsAllBinaryCodesOfSizeKSolution::CheckIfAStringContainsAllBinaryCodesOfSizeKSolution() { |
| 81 | + setMetaInfo({.id = 1461, |
| 82 | + .title = "Check If a String Contains All Binary Codes of Size K", |
| 83 | + .url = "https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/"}); |
| 84 | + registerStrategy("Sliding Window + HashSet", solution1); |
| 85 | + registerStrategy("Sliding Window + Vector", solution2); |
| 86 | +} |
| 87 | + |
| 88 | +bool CheckIfAStringContainsAllBinaryCodesOfSizeKSolution::hasAllCodes(string s, int k) { |
| 89 | + return getSolution()(s, k); |
| 90 | +} |
| 91 | + |
| 92 | +} // namespace problem_1461 |
| 93 | +} // namespace leetcode |
0 commit comments