1884 Minimum Changes To Make Alternating Binary String
1884 Minimum Changes To Make Alternating Binary String
Minimum Changes To Make Alternating Binary String 
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:
1
2
3
4
5
**Input:** s = "0100"
**Output:** 1
**Explanation:** If you change the last character to '1', s will be "0101", which is alternating.
Example 2:
1
2
3
4
5
**Input:** s = "10"
**Output:** 0
**Explanation:** s is already alternating.
Example 3:
1
2
3
4
5
**Input:** s = "1111"
**Output:** 2
**Explanation:** You need two operations to reach "0101" or "1010".
Constraints:
1
2
1 <= s.length <= 104
s[i] is either '0' or '1'.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
impl Solution {
pub fn min_operations(s: String) -> i32 {
/*
let mut prev = -1;
let mut res = 0;
for k in s.chars() {
if prev == -1 {
prev = k as i32;
} else {
if prev == k as i32{
res += 1;
if prev == 0 {
prev = 1;
} else {
prev = 0;
}
} else {
prev = k as i32;
}
}
}
res*/
// greedy failed, too fast
// recursion of all will be too slow
/* fn recurse(s : String) {
let mut prev = -1;
let mut res = 0;
for (i,k) in enumerate(s.chars()) {
if prev == -1 {
prev = k
} else {
if prev == k {
res = 1 + recurse()
} else {
prev = k;
}
}
}
*/
// how abt enumeration ?
// only two possible ans, why not find the smaller diff between two srings
let mut res1 = 0;
let mut res2 = 0;
let mut init1 = 0;
let mut init2 = 1;
for k in s.chars() {
//print!("{}", k.to_digit(10));
if k.to_digit(10).unwrap() != init1 {
res1 += 1;
}
if k.to_digit(10).unwrap() != init2 {
res2 += 1;
}
if init1 == 1 {
init1 = 0;
} else {
init1 = 1;
}
if init2 == 1 {
init2 = 0;
} else {
init2 = 1;
}
}
print!("{} {}", res1, res2);
return res1.min(res2);
}
}
This post is licensed under CC BY 4.0 by the author.