[LeetCode] Binary String With Substrings Representing 1 To N

1016. Binary String With Substrings Representing 1 To N

Given a binary string s and a positive integer n, return true if the binary representation of all the integers in the range [1, n] are substrings of s, or false otherwise.

A substring is a contiguous sequence of characters within a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
bool queryString(string s, int n) {
vector<bool> seen(n+1);
int cnt = 0;
for(int i = 0; i < s.length(); i++) {
if(s[i] == '0') continue;
long long num = 0;
for(int j = i; j < min(i + 31, (int)s.length()); j++) {
num = num * 2 + (s[j] == '1');
if(num <= n and !seen[num]) {
cnt += seen[num] = true;
}
}
}
return cnt == n;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/29/PS/LeetCode/binary-string-with-substrings-representing-1-to-n/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.