You are given a binary string s and a positive integer k.
Return the length of the longest subsequence of s that makes up a binary number less than or equal to k.
Note:
The subsequence can contain leading zeroes.
The empty string is considered to be equal to 0.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
Example 1:
Input: s = “1001010”, k = 5
Output: 5
Explanation: The longest subsequence of s that makes up a binary number less than or equal to 5 is “00010”, as this number is equal to 2 in decimal.
Note that “00100” and “00101” are also possible, which are equal to 4 and 5 in decimal, respectively.
The length of this subsequence is 5, so 5 is returned.
Example 2:
Input: s = “00101001”, k = 1
Output: 6
Explanation: “000001” is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.
The length of this subsequence is 6, so 6 is returned.
Constraints:
- 1 <= s.length <= 1000
- s[i] is either ‘0’ or ‘1’.
- 1 <= k <= 109
做到最后发现这是一道脑筋急转弯, 先说思路, 二进制从右往左每个位上的 1 分别代表 2 的 0 次方、2 的 1 次方、2 的 2 次方。。。。。, 我们每次从 s 的末尾拿一个字符,如果是 1 的话,如果我们要放到我们的结果字符串当中, 就相当于给当前值加了 2 的 n 次方, 这个 n 是当前结果字符串的长度, 如果不放当然值也不增加,长度也不增加。而如果拿出的字符是 0 的话,我们可以放心大胆的把它放到结果字符串中,因为它不会使当前结果字符串的值增加,只会增加长度。所以整体来看, 我们遇到 1 的时候应该是能增就增,因为此时如果你不增,后面结果变长了你更增不起,而如果遇到 0 则只需直接放到结果里就好,因为当前位你不是放 0 就是放 1, 你如果放弃眼前的 0 改等后面的 1,届时同样是增长 1 位,但是放 1 的话值也会相应增加的。
再说脑筋急转弯的问题, 题目里 k 的类型是 i32,也就是最多有 32 个 1, 但是题目里给出的 s.length <= 1000, 所以在我们攒齐了 32 个 1 之后,我们就不需要再去检查 1 的情况了, 只把后面所有的 0 收集起来就好了
impl Solution {
pub fn longest_subsequence(mut s: String, k: i32) -> i32 {
let mut len = 0i64;
let mut val = 0i64;
while let Some(c) = s.pop() {
if c == '1' {
if len > 32 {
continue;
}
let v = 2i64.pow(len as u32);
if val + v <= k as i64 {
val += v;
len += 1;
}
continue;
}
len += 1;
}
len as i32
}
}