LeetCode 926. Flip String to Monotone Increasing (Medium)
A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), followed by some number of '1's (also possibly 0.)
We are given a string S of '0's and '1's, and we may flip any '0' to a '1' or a '1' to a '0'.
Return the minimum number of flips to make S monotone increasing.
Example 1:
Input: "00110"
Output: 1
Explanation: We flip the last digit to get 00111.
Example 2:
Input: "010110"
Output: 2
Explanation: We flip to get 011111, or alternatively 000111.
Example 3:
Input: "00011000"
Output: 2
Explanation: We flip to get 00000000.
Note:
1 <= S.length <= 20000Sonly consists of'0'and'1'characters.
方法:dp
思路:
1 用两个变量维护当遇到当前character的时候,flip成0或者flip成1时候的数量,cnt1,cnt0。
2 当当前character是0的时候,我们可以把它flip成1,cnt1 = min(cnt1,cnt0)+1。因为这个0之前的可能是翻成0的,也可能是翻成1的。所以取两种情况下的最小值。如果character是1的话,我们可以吧它flip成0. 这时候记得要先update
cnt1 = min(cnt1, cnt0)。然后再update cnt0+=1
3 最后返回cnt0和cnt1的最小值即可。
time complexity: O(n) space complexity:O(1)
class Solution: def minFlipsMonoIncr(self, S: str) -> int: if not S or len(S) == 0: return 0 count0 = 0 count1 = 0 for i in range(len(S)): if S[i] == '0': # flip to 1 => two choices, coming from count0 (count0+1) or coming from count1(count1+1) count1 = min(count0, count1) + 1 else: # flip to 0 => one choice, coming from count0, so count0 += 1 count1 = min(count0, count1) count0 += 1 return min(count0, count1)
浙公网安备 33010602011771号