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

 

 

 

 

思路:

这题比较新,关键点在于有个小hint,unique的长为k的binary字符串有且仅有2^{k}个,这点可以通过不完全归纳法来观察得出:当k=1,2种字符串0 和 1;k=2,四种 00 , 01, 10, 11;k=3时,8种,000,001,010,011,100,101,110,111;以此类推。知道了这一点以后,我们可以逆着题目思路来做。如果我们沿着题目思路,需要把当前k的所有可能字符串存起来,然后一段一段地遍历原字符串s,与存起来的字符串做对比,最后再确认是否全部存在。但是这里我们采用逆向思维,一段一段地遍历字符串,将每一段k长度的字串存入一个哈希set,最后检查这个哈希set的size是否为2^{k}即可。

 

 

 

 

代码:

class Solution {
public:
    bool hasAllCodes(string s, int k) {
        if (k > s.size()) return false;
        unordered_set<string> record;
        for (int i = 0; i <= s.size()-k; i++)
            record.insert(s.substr(i, k));
        return record.size() == pow(2, k);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值