描述
You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not.
Return the minimum number of operations needed to make s alternating.
Example 1:
Input: s = "0100"
Output: 1
Explanation: If you change the last character to '1', s will be "0101", which is alternating.
Example 2:
Input: s = "10"
Output: 0
Explanation: s is already alternating.
Example 3:
Input: s = "1111"
Output: 2
Explanation: You need two operations to reach "0101" or "1010".
Note:
1 <= s.length <= 10^4
s[i] is either '0' or '1'.
解析
根据题意,就是将 s 改为 0 和 1 不连续出现的最小步骤,思路简单,当 s 的长度为 N 的时候,只有两种情况以 0 开头和以 1 开头的字符串 a 和 b ,然后用 a 和 b 结合原 s 判断不一样的字符串的出现个数,找出较少的那个即为答案。
解答
class Solution(object):
def minOperations(self, s):
"""
:type s: str
:rtype: int
"""
N = len(s)
a,b = '01'*(N//2), '10'*(N//2)
if N % 2 > 0:
a = a + '0'
b = b + '1'
r1 = 0
r2 = 0
for i in range(N):
if s[i] != a[i]:
r1 += 1
if s[i] != b[i]:
r2 += 1
return min(r1, r2)
运行结果
Runtime: 36 ms, faster than 88.57% of Python online submissions for Minimum Changes To Make Alternating Binary String.
Memory Usage: 13.6 MB, less than 72.14% of Python online submissions for Minimum Changes To Make Alternating Binary String.
原题链接:leetcode.com/problems/mi…
您的支持是我最大的动力