← 筆記

[LeetCode刷題筆記] 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.

Example 1:

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 indicies 0, 1, 3 and 2 respectively.

Example 2:

Input: s = "00110", k = 2
Output: true

Example 3:

Input: s = "0110", k = 1
Output: true
Explanation: The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring.

Example 4:

Input: s = "0110", k = 2
Output: false
Explanation: The binary code "00" is of length 2 and doesn't exist in the array.

Example 5:

Input: s = "0000000001011100", k = 4
Output: false

Constraints:

  • 1 <= s.length <= 5 * 10^5
  • s consists of 0’s and 1’s only.
  • 1 <= k <= 20

一刷題解(HashSet):

這題給了我們一個由0和1組成的字符串s,另外給了我們一個位數k。題目要求我們找出位數為k中的所有二進制碼是否被全部包含在了字符串s的子字符串中(長度同樣為k)。因此,這個k分別代表了我們每次在字符中所要提取的子字符串長度和我們要進行比較的二進制碼長度。

首先,由於我們每次遍歷字符串s都要取出長度為k的子字符串,因此,我們遍歷字符串s的次數上限是s.Length - k,確保不會越界。然後我們聲明一個HashSet,並把我們在字符串s中取出的元素逐一加進HashSet中。而由於HashSet本身的特性,已存在HashSet中的元素不會被重複添加,於是最後我們得到一個長度為字符串s中,位數為k的二進制碼種數。

然後,只要我們再將這個種數(set.Count)跟位數為k下的所有二進制碼數量(Math.Pow(2, k))進行比較。如果兩者相等,那就意味著k位的所有二進制碼全部被包含在字符串s中長度為k的子字符串之中。

public class Solution {
    public bool HasAllCodes(string s, int k) {    
        HashSet<string> set = new HashSet<string>();
        for (int i = 0; i <= s.Length - k; i++)
        {
            string str = s.Substring(i, k);
            set.Add(str);
        }

        //every binary code of length k = Math.Pow(2, k);
        //set should be include all single binary code of 2*k
        //return Math.Pow(2, k) == set.Count;
        return (1 << k) == set.Count;
    }
}