https://leetcode.com/problems/minimum-number-of-changes-to-make-binary-string-beautiful
2914. Minimum Number of Changes to Make Binary String Beautiful
给一个长度为偶数、索引起始为0的二进制字串 s
beautiful 的条件是
每个子字串的长度都是偶数
每个子字串只包含1或只包含0
可以将s中的任何字符改成0或1
回传变成beautiful的最少更改次数
Example 1:
Input: s = "1001"
Output: 2
Explanation: s[1] 换成 1 s[3] 换成0 变成 "11 | 00"
Example 2:
Input: s = "10"
Output: 1
Example 3:
Input: s = "0000"
Output: 0
Constraints:
2 <= s.length <= 10^5
s 长度为偶数
s[i] 只有 '0' 或 '1'
思路:
字符两两相比 不同就+1
range用2可以加快判断速度
Python Code:
class Solution:
def minChanges(self, s: str) -> int:
if len(set(s)) == 1:
return 0
cnt = 0
for i in range(0, len(s), 2):
if s[i] != s[i+1]:
cnt += 1
return cnt
或是直接一行
return sum(s[i] != s[i+1] for i in range(0, len(s), 2))