[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。所以这里改正的方式是

  • 我们每遍历一个字符串的时候,如果一开始出现的都是 0,还未出现过 1,则一直往前走
  • 从遇到第一个 1 开始,我们就开始统计 1 出现的次数,记为 oneCount
  • 出现过 1 之后,如果后面再出现 0,我们则记录一个 flipCount 的次数,意思是记录我们把多少个 0 改成了 1

最后我们返回的是 flipCount 和 oneCount 的较小值,意思是看看到底翻转什么数字的代价比较小。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int minFlipsMonoIncr(String s) {
 3         int oneCount = 0;
 4         int flipCount = 0;
 5         for (char c : s.toCharArray()) {
 6             if (c == '0') {
 7                 if (oneCount == 0) {
 8                     continue;
 9                 } else {
10                     flipCount++;
11                 }
12             } else {
13                 oneCount++;
14             }
15             if (flipCount > oneCount) {
16                 flipCount = oneCount;
17             }
18         }
19         return flipCount;
20     }
21 }

 

LeetCode 题目总结 

posted @ 2021-01-17 06:08  CNoodle  阅读(77)  评论(0编辑  收藏  举报