1. 程式人生 > >LeetCode-Flip String to Monotone Increasing

LeetCode-Flip String to Monotone Increasing

Description: 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 <= S.length <= 20000
  • S only consists of ‘0’ and ‘1’ characters.

題意:對字串定義單調為——一定數量的字元‘0’(個數可能為0)後接一定數量的字元‘1’(個數可能為0);現給定一個字串(僅包含字元‘0’與‘1’),計算最小可經過多少次的翻轉(‘0’->'1’或‘1’->‘0’),使得這個字串為單調的;

解法:可以考慮窮舉法,既然要求字串的開始部分為一定數量的字元’0’,那麼我們可以找到出現的第一個字元’1‘,將其後所有的字元’0’翻轉,得到翻轉次數;之後再重複上述操作,找到出現的第二個字元‘1’,再將其後的所有字元‘0’翻轉,注意此時的翻轉次數需要加上前面出現的字元‘1’的個數;最後,返回翻轉次數最小的那個; 這裡,我們可以考慮減少計算的次數,假如,當我們要找第i個字元‘1’時,如果此時前面已經出現過的字元‘1’已經比此時我們計算所得最小翻轉次數還要大,那麼就不需要進行後續的計算了,因此,之後所得到的翻轉次數必然比當前已經得到的最小翻轉次數來的大;

Java
class Solution {
    public int minFlipsMonoIncr(String S) {
        int base = 0;
        int minFlip = Integer.MAX_VALUE;
        for (int i = 0; i < S.length();) {
            if (base > minFlip) break;
            int index = i;
            int cnt = 0;
            while (index < S.length() && S.charAt(index) == '0') index++;
            for (int j = index + 1; j < S.length(); j++) {
                cnt = S.charAt(j) == '0' ? cnt + 1 : cnt;
            }
            minFlip = Math.min(minFlip, cnt + base);
            base++;
            i = index + 1;
        }
        return minFlip;
    }
}