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.
隔离第五天 终于喝到酸奶啦>o<
思路:长度一定的交替二进制字符串有两种可能性,以字符0开头的0101字符串和以字符1开头的1010字符串,因此只需要将字符串s与这两种字符串进行比较,记录不相同的字符个数,最后返回较小值即可
实现:使用异或操作记录该位应是1还是0:flag ^= 1;
class Solution {
public int minOperations(String s) {
return Math.min(countOperations(s,0),countOperations(s,1));
}
public int countOperations(String s, int flag){
int n = s.length();
int count = 0;
for (int i = 0; i < n; i++){
if (s.charAt(i) == '0' + flag){
count++;
}
flag ^= 1;
}
return count;
}
}
复杂度分析
优化:变成这两种不同的交替二进制字符串所需要的最少操作数加起来等于 s的长度,我们只需要计算出变为其中一种字符串的最少操作数,就可以推出另一个最少操作数,然后取最小值即可。
class Solution {
public int minOperations(String s) {
int n = s.length();
int n0 = countOperations(s,0);
return Math.min(n-n0, n0);
}
public int countOperations(String s, int flag){
int n = s.length();
int count = 0;
for (int i = 0; i < n; i++){
if (s.charAt(i) == '0' + flag){
count++;
}
flag ^= 1;
}
return count;
}
}
复杂度分析
但是还没第一种快