题目来源:https://leetcode.com/contest/weekly-contest-107/problems/flip-string-to-monotone-increasing/
问题描述
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和1组成的字符串,定义“翻转”为将一个0变成1或一个1变成0,定义“递增”为字符串中没有1出现在0之前。问对于给定的字符串,至少多少次翻转可以将其变成递增字符串。
------------------------------------------------------------
思路
计算s[0:i]和s[i:len]中的0和1的个数,i=0,1,2,…,len,保存在两个数组cnt0和cnt1中;
枚举len+1种情况(i=0,1,2,…,len),借助cnt0和cnt1计算将s[0:i]全部变为0和s[i:len]全部变为1的翻转次数,取len+1种情况的最小值。
O(n)算法。
------------------------------------------------------------
代码
class Solution {
public:
int cnt0[20005] = {};
int cnt1[20005] = {};
int minFlipsMonoIncr(string S) {
int i = 0, len = S.size(), ans = 0x3f3f3f3f;
for (i=0; i<len; i++)
{
if (S[i] == '0')
{
cnt0[i+1] = cnt0[i] + 1;
cnt1[i+1] = cnt1[i];
}
else
{
cnt0[i+1] = cnt0[i];
cnt1[i+1] = cnt1[i] + 1;
}
}
for (i=0; i<=len; i++)
{
ans = min(ans, cnt1[i] + cnt0[len] - cnt0[i]);
}
return ans;
}
};