LeetCode 926. Flip String to Monotone Increasing (将字符串翻转到单调递增)

题目标签:Array

  为了实现单调递增,需要把某些0变成1,或者某些1变成0,而且要返回的是“最少的反转次数”,这里要分两种情况:

  1. 当 i - 1 是0: 那么 i 这个数字是0 或者 1 的话 都是递增;

  2. 当 i - 1 是1: 那么 i 需要是 1 才能 继续保持递增。

  利用动态规划,设 dp0 和 dp1 两个 array, dp0 以 i - 1 是 0 来记录;dp1 以 i - 1 是 1 来记录,具体看code。

  

  

 

Java Solution: 

Runtime:  5 ms, faster than 27.11% 

Memory Usage: 39.6 MB, less than 20.00 %

完成日期:4/04/2020

关键点:DP

class Solution {
    public int minFlipsMonoIncr(String S) {
        int[] dp0 = new int[S.length()];
        int[] dp1 = new int[S.length()];
        dp0[0] = S.charAt(0) == '0' ? 0 : 1;
        dp1[0] = S.charAt(0) == '1' ? 0 : 1;
        
        for(int i = 1; i < S.length(); i++) {
            dp0[i] = dp0[i-1] + (S.charAt(i) == '0' ? 0 : 1);
            dp1[i] = Math.min(dp0[i-1], dp1[i-1]) + (S.charAt(i) == '1' ? 0 : 1);
        }
        
        return Math.min(dp0[S.length() - 1], dp1[S.length() - 1]);
    }
}

参考资料:https://zhuanlan.zhihu.com/p/54680039

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2020-04-06 05:08  Jimmy_Cheng  阅读(192)  评论(0编辑  收藏  举报