2311. 小于等于 K 的最长二进制子序列
丑陋的代码,边界问题改半天
class Solution {
public:
int calc(string s){
int x = 0;
for(auto c: s){
x <<= 1;
if(c=='1') x+=1;
}
return x;
}
int longestSubsequence(string s, int k) {
int one = 0, zero = 0;
int n = s.size();
if(n > 31) {
for(int i = 0; i < n - 31; i++ ) {
if(s[i] == '1') one++;
}
s = s.substr(n-31);
}
int cur = calc(s);
if(cur<=k) return n - one;
for(int i =0; i < s.size(); i++) {
cur = calc(s.substr(i));
if(cur <= k) return n - one;
if(s[i] == '1') one++;
}
return 0;
}
};
网友评论