题目:
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字符串有且仅有个,这点可以通过不完全归纳法来观察得出:当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是否为即可。
代码:
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);
}
};