Question Link

https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/

Question Description

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.
Input: s = “00110110”, k = 2
Output: true
Explanation: The binary codes of length 2 are “00”, “01”, “10” and “11”. They can be all found as substrings at indices 0, 1, 3 and 2 respectively.

Simulation

Solution 1: SlideWindow + Hashset

Step 1: Define a hashset
Step 2: Traverse the string by adding all the elements into the set
Step 3: Check if the set equals the number of combination from k

Solution 2: SlideWindow + Hash-Like Array + Bit

Leetcode 1461 Check If a String Contains All Binary Codes of Size K - 图1

Implementation

Solution 1: Sliding Window

  1. public boolean hasAllCodes(String s, int k) {
  2. Set <String> set = new HashSet < > ();
  3. if (s.length() - k < 0) return false;
  4. for (int i = 0; i <= s.length() - k; i++)
  5. set.add(s.substring(i, i + k));
  6. return set.size() == Math.pow(2, k);
  7. }

Solution 2: Bit+Sliding Window

  1. public boolean hasAllCodes(String s, int k) {
  2. if (s.length() < k) return false;
  3. boolean[] combination = new boolean[1 << k];
  4. int size = combination.length;
  5. int bit = 0;
  6. for (int i = 0; i < k; i++) {
  7. bit = bit << 1;
  8. bit = bit ^ (s.charAt(i) - '0');
  9. }
  10. combination[bit] = true;
  11. size--;
  12. for (int i = k; i < s.length(); i++) {
  13. bit = bit << 1;
  14. bit = bit & ~(1 << k);
  15. bit = bit ^ (s.charAt(i) - '0');
  16. if (combination[bit] == false) {
  17. combination[bit] = true;
  18. size--;
  19. }
  20. if (size == 0) {
  21. return true;
  22. }
  23. }
  24. return false;
  25. }