926. Flip String to Monotone Increasing [Medium]

https://leetcode.com/problems/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. 1 <= S.length <= 20000
  2. S only consists of '0' and '1' characters.

算法思路:

转换0-1字符串使得字符串非单调减小

方法1:greedy

一旦发现后面0的个数超过前面1的个数,那么这一段中,0和1必须转换一种才能保证非单减,转换1到0操作数少,接着进行下面一段的贪心操作,最终答案就是res + numbOf0(如果numberOf == 0,表示最后全是0,否则表示最后这一段全部是1,这段0要转换成1,转换操作数就是numbOf0,综上都是res + numbOf0)。

class Solution {
public:
    int minFlipsMonoIncr(string S) {
        int n = S.size();
        int numbOf1 = 0;
        int numbOf0 = 0;
        int res = 0;
        for (int i = 0; i < n; i++) {
            if (S[i] == '1') numbOf1++;
            else numbOf0++;
            // flip those ones to zeros cause it is cheaper
            if (numbOf0 > numbOf1) {
                res += numbOf1;
                numbOf1 = 0;
                numbOf0 = 0;
            }
        }
        return res + numbOf0;
    }
};

方法2:dp

  • dp[i]:表示处于位置i的时候,保证0-1字符串非单减需要的最少转换操作数
  • S[i] == '1',直接加到numbOf1,dp[i] = dp[i - 1] ,S[i] == '0'保持不变则前面的1都要变成0,0变成1,那么转化步骤+1
  • 这里简化了dp维度,使空间复杂度将为O(1)
// dp[0] = 0
// dp[i] = dp[i - 1]             (S[i] == '1')
//       = min(numbOf1, dp + 1)  (S[i] == '0')
class Solution {
public:
    int minFlipsMonoIncr(string S) {
        int n = S.size();
        int numbOf1 = 0;
        int dp = 0;
        for (int i = 0; i < n; i++) {
            if (S[i] == '1') numbOf1++; // dp = dp is not necessary to write it!
            else dp = min(numbOf1, dp + 1);
        }
        return dp;
    }
};

参考资料: 

https://leetcode.com/problems/flip-string-to-monotone-increasing/solution/  (看文章下面的评论)

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页