注意到,变成这两种不同的交替二进制字符串所需要的最少操作数加起来等于 s 的长度,我们只需要计算出变为其中一种字符串的最少操作数,就可以推出另一个最少操作数,然后取最小值即可。
代码
[sol1-Python3]
1 2 3 4
classSolution: defminOperations(self, s: str) -> int: cnt = sum(int(c) != i % 2for i, c inenumerate(s)) returnmin(cnt, len(s) - cnt)
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { publicintminOperations(String s) { intcnt=0; for (inti=0; i < s.length(); i++) { charc= s.charAt(i); if (c != (char) ('0' + i % 2)) { cnt++; } } return Math.min(cnt, s.length() - cnt); } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12
publicclassSolution { publicintMinOperations(string s) { int cnt = 0; for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c != (char) ('0' + i % 2)) { cnt++; } } return Math.Min(cnt, s.Length - cnt); } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public: intminOperations(string s){ int cnt = 0; for (int i = 0; i < s.size(); i++) { char c = s[i]; if (c != ('0' + i % 2)) { cnt++; } } returnmin(cnt, (int)s.size() - cnt); } };
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12
#define MIN(a, b) ((a) < (b) ? (a) : (b))
intminOperations(char * s) { int cnt = 0, len = strlen(s); for (int i = 0; i < len; i++) { char c = s[i]; if (c != ('0' + i % 2)) { cnt++; } } return MIN(cnt, len - cnt); }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10
var minOperations = function(s) { let cnt = 0; for (let i = 0; i < s.length; i++) { const c = s[i]; if (c !== (String.fromCharCode('0'.charCodeAt() + i % 2))) { cnt++; } } returnMath.min(cnt, s.length - cnt); };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
funcminOperations(s string)int { cnt := 0 for i, c := range s { if i%2 != int(c-'0') { cnt++ } } return min(cnt, len(s)-cnt) }
funcmin(a, b int)int { if a > b { return b } return a }