Given a binary string s and a positive integer n, return trueif the binary representation of all the integers in the range[1, n]_aresubstrings of _s, orfalseotherwise.
A substring is a contiguous sequence of characters within a string.
To check if all binary representations of numbers from 1 to n are substrings of s, we can generate all such binary strings and check if each is present in s. To optimize, we can use a set to store all substrings of s of relevant lengths and compare.
classSolution {
public:bool queryString(string s, int n) {
for (int k = n; k >=1; --k) {
string t;
int x = k;
while (x) {
t += (x %2) +'0';
x /=2;
}
reverse(t.begin(), t.end());
if (s.find(t) == string::npos) return false;
}
return true;
}
};
classSolution {
publicbooleanqueryString(String s, int n) {
for (int k = n; k >= 1; --k) {
String t = Integer.toBinaryString(k);
if (!s.contains(t)) returnfalse;
}
returntrue;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funqueryString(s: String, n: Int): Boolean {
for (k in n downTo 1) {
val t = Integer.toBinaryString(k)
if (!s.contains(t)) returnfalse }
returntrue }
}
1
2
3
4
5
6
classSolution:
defqueryString(self, s: str, n: int) -> bool:
for k in range(n, 0, -1):
if bin(k)[2:] notin s:
returnFalsereturnTrue
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnquery_string(s: String, n: i32) -> bool {
for k in (1..=n).rev() {
let t =format!("{:b}", k);
if!s.contains(&t) {
returnfalse;
}
}
true }
}