题目链接:https://leetcode.cn/problems/longest-binary-subsequence-less-than-or-equal-to-k/description/
题目大意:给一个01字符串s
和一个正整数k
,求一个最长的子串,满足【其值转换为十进制小于k
】。子串可以删除中间若干元素得到。
思路:没思路,G。看题解只感叹这idea真美妙。
首先,对于转换成十进制的值,s
中只有1
起作用,0
并不会贡献值。考虑到子串可以删除中间元素,那么不妨先考虑删掉所有的1
,也就是取走所有的0
。此时值为0
,肯定小于等于k
。
然后,因为子串元素的位置是不能改变的,因此我们考虑从末尾找1
,逐个加入,这样就能保证每次加入的值是最小的。找到那个最大的小于k
的值,记录加入的1
的数量和原本0
的数量即可。
完整代码
class Solution {
public:
int longestSubsequence(string s, int k) {
int res = 0;
for (auto c : s) {
if (c == '0')
res++;
}
// w is the value to be added if we choose 1 in this position
// ans is the sum for now, it should be <= k
long long w = 1, ans = 0;
for (int i = s.length()-1; i >= 0 && w < 2e9; i--, w <<= 1) {
if (s[i] == '1') {
ans += w;
if (ans > k)
return res;
res++;
}
}
return res;
}
};