跳转至

1758. 生成交替二进制字符串的最少操作数

题目描述

给你一个仅由字符 '0''1' 组成的字符串 s 。一步操作中,你可以将任一 '0' 变成 '1' ,或者将 '1' 变成 '0'

交替字符串 定义为:如果字符串中不存在相邻两个字符相等的情况,那么该字符串就是交替字符串。例如,字符串 "010" 是交替字符串,而字符串 "0100" 不是。

返回使 s 变成 交替字符串 所需的 最少 操作数。

 

示例 1:

输入:s = "0100"
输出:1
解释:如果将最后一个字符变为 '1' ,s 就变成 "0101" ,即符合交替字符串定义。

示例 2:

输入:s = "10"
输出:0
解释:s 已经是交替字符串。

示例 3:

输入:s = "1111"
输出:2
解释:需要 2 步操作得到 "0101" 或 "1010" 。

 

提示:

  • 1 <= s.length <= 104
  • s[i]'0''1'

解法

方法一:一次遍历

根据题意,如果得到交替字符串 01010101... 所需要的操作数为 \(\textit{cnt}\),那么得到交替字符串 10101010... 所需要的操作数为 \(n - \textit{cnt}\)

因此,我们只需要遍历一次字符串 \(s\),统计出 \(\textit{cnt}\) 的值,那么答案即为 \(\min(\textit{cnt}, n - \textit{cnt})\)

时间复杂度 \(O(n)\),其中 \(n\) 为字符串 \(s\) 的长度。空间复杂度 \(O(1)\)

1
2
3
4
class Solution:
    def minOperations(self, s: str) -> int:
        cnt = sum(c != '01'[i & 1] for i, c in enumerate(s))
        return min(cnt, len(s) - cnt)
1
2
3
4
5
6
7
8
9
class Solution {
    public int minOperations(String s) {
        int cnt = 0, n = s.length();
        for (int i = 0; i < n; ++i) {
            cnt += (s.charAt(i) != "01".charAt(i & 1) ? 1 : 0);
        }
        return Math.min(cnt, n - cnt);
    }
}
1
2
3
4
5
6
7
8
class Solution {
public:
    int minOperations(string s) {
        int cnt = 0, n = s.size();
        for (int i = 0; i < n; ++i) cnt += s[i] != "01"[i & 1];
        return min(cnt, n - cnt);
    }
};
1
2
3
4
5
6
7
8
9
func minOperations(s string) int {
    cnt := 0
    for i, c := range s {
        if c != []rune("01")[i&1] {
            cnt++
        }
    }
    return min(cnt, len(s)-cnt)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function minOperations(s: string): number {
    let cnt = 0;
    const n = s.length;
    for (let i = 0; i < n; ++i) {
        if (s[i] !== '01'[i & 1]) {
            ++cnt;
        }
    }
    return Math.min(cnt, n - cnt);
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
impl Solution {
    pub fn min_operations(s: String) -> i32 {
        let mut cnt: i32 = 0;
        let n: i32 = s.len() as i32;
        let bytes = s.as_bytes();

        for i in 0..n as usize {
            if bytes[i] != b"01"[i & 1] {
                cnt += 1;
            }
        }

        cnt.min(n - cnt)
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
int minOperations(char* s) {
    int cnt = 0;
    int n = strlen(s);
    for (int i = 0; i < n; ++i) {
        if (s[i] != "01"[i & 1]) {
            ++cnt;
        }
    }
    return cnt < (n - cnt) ? cnt : (n - cnt);
}

评论