zoukankan      html  css  js  c++  java
  • [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. 1 <= S.length <= 20000
    2. S only consists of '0' and '1' characters.

    将字符串翻转到单调递增。

    如果一个由 '0' 和 '1' 组成的字符串,是以一些 '0'(可能没有 '0')后面跟着一些 '1'(也可能没有 '1')的形式组成的,那么该字符串是单调递增的。

    我们给出一个由字符 '0' 和 '1' 组成的字符串 S,我们可以将任何 '0' 翻转为 '1' 或者将 '1' 翻转为 '0'。

    返回使 S 单调递增的最小翻转次数。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/flip-string-to-monotone-increasing
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    这是一道数组的题目,但是这里面有一点贪心的思想。我的思路如下,对 input 字符串从左往右扫描,因为题目最后要求的是翻转过后,input 的左边都是 0,右边都是 1,所以当我遇到第一个 1 的时候,我就假设我现在往后遇到的都是 1 了,0 我已经在之前都遇到过了。但是从此刻开始,如果再遇到 0 的话,我就用一个变量 flip 记录我需要把多少个 0 翻转成 1;同时我从遇到的第一个 1 开始,用另一个变量 countOne 记录我一共遇到多少个 1。最后遍历完 input 字符串,取 flip 和 countOne 的较小值。

    但是这个思路在遇到一些不是很长的 case 的时候就会出错,原因在于我们这样统计的时候,只是单纯地把 0 改成 1,从没有把 1 改成 0。所以这里改正的方式就是我们每遍历一个字符串的时候,我们就统计 flip 的个数和 1 出现的个数。如果 1 出现的个数小于 flip 的个数的话,那么我们可以把这些 1 翻转成 0,这样代价会小一点。这个思路有那么一点局部贪心的感觉。

    时间O(n)

    空间O(1)

    Java实现

     1 class Solution {
     2     public int minFlipsMonoIncr(String S) {
     3         int countOne = 0;
     4         int flip = 0;
     5         for (int i = 0; i < S.length(); i++) {
     6             if (S.charAt(i) == '0') {
     7                 if (countOne == 0) {
     8                     continue;
     9                 } else {
    10                     flip++;
    11                 }
    12             } else {
    13                 countOne++;
    14             }
    15             if (flip > countOne) {
    16                 flip = countOne;
    17             }
    18         }
    19         return flip;
    20     }
    21 }

    LeetCode 题目总结 

  • 相关阅读:
    hdu2844 Coins -----多重背包+二进制优化
    bzoj1452 [JSOI2009]Count ——二维树状数组
    cf685 div2 abcde
    cf675 div2 abcd
    cf669 div2 abcd
    cf668 div2 abcd
    UVA-10795
    cf665 div2 abcd
    Colored Cubes UVALive
    Image Is Everything UVALive
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14288169.html
Copyright © 2011-2022 走看看