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
ton-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.
思路:这题就是用一个变量记录flip了多少次,这个变量其实也代表了后面flip了多少次,那么再跟当前的0,1判断就可以知道当前是否需要flip;
class Solution {
public int minFlips(String target) {
int n = target.length();
char[] tt = target.toCharArray();
int count = 0;
for(int i = 0; i < tt.length; i++) {
if(tt[i] == '1') {
if(count % 2 == 0) {
count++;
}
} else {
if(count % 2 != 0) {
count++;
}
}
}
return count;
}
}