【leetcode】926.Flip String to Monotone Increasing
题目如下:
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 <= 20000
S
only consists of'0'
and'1'
characters.
解题思路:转换后的字符串有两种形式,一个是全为0,另一个是前半部分全是0后半部分全是1。第一种情况的翻转次数是S中1的个数;第二种的情况,我们只要找出转换后的字符串第一个1所在的位置即可。设第一个所在的位置是i,那么S[0:i-1]区间内所有1都要变成0,而S[i:-1]区间内所有的0要变成1,总的翻转次数就是前一段区间内1的个数加上后一段区间内0的个数即可。遍历S,即可求出第二种情况的最小值,再与第一种情况求得的值比较取最小值即可。
代码如下:
class Solution(object): def minFlipsMonoIncr(self, S): """ :type S: str :rtype: int """ t_count_1 = S.count('1') t_count_0 = len(S) - t_count_1 res = t_count_1 count_0 = 0 count_1 = 0 for i,v in enumerate(S): if v == '0': count_0 += 1 else: #count_1 += 1 # if convert this 1 to 0 res = min(res,count_1 + (t_count_0 - count_0)) count_1 += 1 return res