[leetcode] 1529. Bulb Switcher IV

Description

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

Constraints:

  • 1 <= target.length <= 10^5
  • target[i] == ‘0’ or target[i] == ‘1’

分析

题目的意思是:给定一个target,问从二进制全0开始根据规则最少经过几步得到target。这道题需要模拟找规律,从左往后找到出现1的位置开始遍历,然后统计有多少个连续相同字符串就是最终的结果了,因为根据规则,从左到右只需要一步就可以把相邻相同的字符串转换成target,所以找出这些target相邻相同的字符串就是结果了。

代码

class Solution:
    def minFlips(self, target: str) -> int:
        cnt=1
        i=0
        n=len(target)
        while(i<n and target[i]=='0'):
            i+=1
        if(i==n):
            return 0
        prev=target[i]
        res=1
        while(i<n):
            if(prev!=target[i]):
                prev=target[i]
                res+=1
            i+=1
        return res

参考文献

[LeetCode] Python 0(N) solution

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值