1529. Bulb Switcher IV

There is a room with n bulbs, numbered from 0 to n-1, arranged in a row from left to right. Initially all the bulbs are turned off.

Your task is to obtain the configuration represented by target where target[i] is '1' if the i-th bulb is turned on and is '0' if it is turned off.

You have a switch to flip the state of the bulb, a flip operation is defined as follows:

  • Choose any bulb (index i) of your current configuration.
  • Flip each bulb from index i to n-1.

When any bulb is flipped it means that if it is 0 it changes to 1 and if it is 1 it changes to 0.

Return the minimum number of flips required to form target.

Example 1:

Input: target = "10111"
Output: 3
Explanation: Initial configuration "00000".
flip from the third bulb:  "00000" -> "00111"
flip from the first bulb:  "00111" -> "11000"
flip from the second bulb:  "11000" -> "10111"
We need at least 3 flip operations to form target.

Example 2:

Input: target = "101"
Output: 3
Explanation: "000" -> "111" -> "100" -> "101".

Example 3:

Input: target = "00000"
Output: 0

Example 4:

Input: target = "001011101"
Output: 5
class Solution {
    public int minFlips(String target) {
        int res = 0;
        
        for (int i = 0; i < target.length(); ++i) {
            // res == how many times it has been flipped so far for bulb i
            if (((res % 2) == 0 && target.charAt(i) == '1') || // unchanged, but need to flip to 1
                ((res % 2) == 1 && target.charAt(i) == '0')) { // changed, but target is 0

                ++res;
            }
        }

        return res;
    }
}

问的是执行几次操作能变成target的模样

操作:从i开始到n-1全部toggle

多谢毛利小五郎指点

 https://leetcode.com/problems/bulb-switcher-iv/discuss/755828/Java-Detailed-Explanation-Greedy-O(N)-One-Pass

class Solution {
   public int minFlips(String target) {
        char prev = '0';
        int res = 0;
        for (char c : target.toCharArray()) {
            if (c != prev) {
                prev = c;
                res++;
            }
        }
        return res;
    }
}

https://leetcode.com/problems/bulb-switcher-iv/discuss/755782/Java-1-loop-O(N)

但是紫霞仙子的方法更胜一筹

猜你喜欢

转载自www.cnblogs.com/wentiliangkaihua/p/13383427.html
IV