如果一个二进制字符串,是以一些 0(可能没有 0)后面跟着一些 1(也可能没有 1)的形式组成的,那么该字符串是 单调递增 的。
给你一个二进制字符串 s,你可以将任何 0 翻转为 1 或者将 1 翻转为 0 。
返回使 s 单调递增的最小翻转次数。
var minFlipsMonoIncr = function(s) {
let s0 = s1 = 0
for (let i = 0; i < s.length; i++) {
s1 = Math.min(s0, s1) + 1 - s[i]
s0 += +s[i]
}
return Math.min(s0, s1)
};
function minFlipsMonoIncr(s: string): number {
let s0 = 0, s1 = 0
for (let i = 0; i < s.length; i++) {
s1 = Math.min(s0, s1) + 1 - +s[i]
s0 += +s[i]
}
return Math.min(s0, s1)
};
class Solution {
function minFlipsMonoIncr($s) {
$s0 = $s1 = 0;
$n = strlen($s);
for ($i = 0; $i < $n; $i++) {
$s1 = min($s0, $s1) + 1 - $s[$i];
$s0 += $s[$i];
}
return min($s0, $s1);
}
}
func minFlipsMonoIncr(s string) int {
s0, s1 := 0, 0
for _, c := range s {
s1 = min(s0, s1) + 1 - (int(c) - 48)
s0 += int(c) - 48
}
return min(s0, s1)
}
func min(a int, b int) int {
if a < b {
return a
}
return b
}
class Solution {
public int minFlipsMonoIncr(String s) {
int s0 = 0, s1 = 0;
char[] chars = s.toCharArray();
for (char c : chars) {
s1 = Math.min(s0, s1) + '1' - c;
s0 += c - '0';
}
return Math.min(s0, s1);
}
}
class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
s0, s1 = 0, 0
for _, c in enumerate(s):
s1 = min(s0, s1) + 1 - int(c)
s0 += int(c)
return min(s0, s1)
int minFlipsMonoIncr(char * s){
int s0 = 0, s1 = 0;
int n = strlen(s);
for (int i = 0; i < n; i++) {
s1 = min(s0, s1) + 1 - s[i] + 48;
s0 += s[i] - 48;
}
return min(s0, s1);
}
int min(int a, int b) {
return a < b ? a : b;
}
class Solution {
public:
int minFlipsMonoIncr(string s) {
int s0 = 0, s1 = 0;
for (char c : s) {
s1 = min(s0, s1) + 1 - c + 48;
s0 += c - 48;
}
return min(s0, s1);
}
};
public class Solution {
public int MinFlipsMonoIncr(string s) {
int s0 = 0, s1 = 0;
int n = s.Length;
for (int i = 0; i < n; i++) {
s1 = Math.Min(s0, s1) + 1 - s[i] + 48;
s0 += s[i] - 48;
}
return Math.Min(s0, s1);
}
}