LeetCode周赛#107 Q2 Flip String to Monotone Increasing

题目来源: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. 1 <= S.length <= 20000
  2. 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;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值