926. Flip String to Monotone Increasing [Medium]

本文介绍了一种算法,用于计算将二进制字符串转换为单调递增所需的最小翻转次数。通过两种方法——贪婪算法和动态规划,实现了高效求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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/  (看文章下面的评论)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值