1. 程式人生 > >LeetCode周賽#107 Q2 Flip String to Monotone Increasing

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;
    }
};