Keep creating , Accelerate growth ! This is my participation 「 Nuggets day new plan · 6 Yuegengwen challenge 」 Of the 31 God , Click to see the event details
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:
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.
Note:
1 <= s.length <= 1000
s[i] is either '0' or '1'.
1 <= k <= 10^9
According to the meaning , Given a binary string s And a positive integer k . Returns a composition less than or equal to k Of binary numbers s The length of the longest subsequence of .
There are :
This question examines greedy thoughts , Suppose we now have a length of 1 Binary string of , If you add... To its left 0 It won't change size , But it will increase the length , This meets the requirement of finding the longest subsequence , All add... On the left as far as possible 0 , Add to its left 1 Will multiply its original size by two , So we have to let 1 Try to keep to the right , So we can add more and more on the left 1 Find a bigger number , The title requires finding one with the largest length and no more than k Binary subsequence of , We can traverse from back to front s , First, find out just no more than k Binary string of , And then add all the left 0 Is the length of the final result .
The time complexity is O(N) , The space complexity is O(N) .
class Solution(object):
def longestSubsequence(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
N = len(s)
for i in range(1, N+1):
if s[-i] == '1':
a = int(s[-i:], 2)
if a > k:
return s[:-i+1].count('0') + (i-1)
return len(s)
153 / 153 test cases passed.
Status: Accepted
Runtime: 46 ms
Memory Usage: 13.6 MB
leetcode.com/contest/wee…
Your support is my greatest motivation