LeetCode每日一题(2311. Longest Binary Subsequence Less Than or Equal to K)

给定一个二进制字符串s和正整数k,找到s中最长的子序列,该子序列组成的二进制数不大于k。文章提供了问题的解析和思路,包括如何处理0和1的情况,以及当k达到一定长度后如何选择子序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值