func minFlipsMonoIncr(_ s: String) -> Int {
let array = Array(s)
let len = array.count
//初始化数据
let temp = Array.init(repeating: 0, count: 2)
var dp = Array.init(repeating: temp, count: len)
if array[0] == "0" {
// dp[0][0] = 0
dp[0][1] = 1
}
else{
dp[0][0] = 1
// dp[0][1] = 0
}
for i in 1..<len {
//如果第i个是0的话 反转为0单调递增所需要的最小次数是
dp[i][0] = dp[i - 1][0] + (array[i] == "0" ? 0 : 1)
dp[i][1] = min(dp[i - 1][0], dp[i - 1][1]) + (array[i] == "1" ? 0 : 1)
}
return min(dp[len - 1][0],dp[len - 1][1])
}
网友评论