Description
You are given a binary string s.
You can perform the following operation on the string any number of times:
- Choose any index
ifrom the string wherei + 1 < s.lengthsuch thats[i] == '1'ands[i + 1] == '0'. - Move the character
s[i]to the right until it reaches the end of the string or another'1'. For example, fors = "010010", if we choosei = 1, the resulting string will bes = "000110".
Return the maximum number of operations that you can perform.
Β
Example 1:
Input: s = "1001101"
Output: 4
Explanation:
We can perform the following operations:
- Choose index
i = 0. The resulting string iss = "0011101". - Choose index
i = 4. The resulting string iss = "0011011". - Choose index
i = 3. The resulting string iss = "0010111". - Choose index
i = 2. The resulting string iss = "0001111".
Example 2:
Input: s = "00111"
Output: 0
Β
Constraints:
1 <= s.length <= 105s[i]is either'0'or'1'.
Solution
Python3
class Solution:
def maxOperations(self, s: str) -> int:
N = len(s)
prevOnes = 0
res = 0
index = 0
while index < N:
if s[index] == "1":
j = index + 1
hasGap = False
while j < N and s[j] == "0":
hasGap = True
j += 1
prevOnes += 1
if hasGap:
res += prevOnes
index = j
else:
index += 1
return res