当前位置:网站首页>926. Flip String to Monotone Increasing

926. Flip String to Monotone Increasing

2022-06-11 23:57:00 SUNNY_CHANGQI

The description of the problem

A binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none).

You are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0.

Return the minimum number of flips to make s monotone increasing.

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/flip-string-to-monotone-increasing

an example

Input: s = "00110"
Output: 1
Explanation: We flip the last digit to get 00111.

The codes for above problem

#include <string>
#include <iostream>
using namespace std;
class Solution {
    
public:
    int minFlipsMonoIncr(string &s){
    
        int n = s.size();
        int dp[n+1][2];
        dp[0][0] = 0;
        dp[0][1] = 0;
        for (int i = 0; i < n; i++) {
    
            dp[i+1][0] = dp[i][0] + ((s[i] == '1') ? 1 : 0);
            dp[i+1][1] = min(dp[i][0], dp[i][1]) + ((s[i] == '0') ? 1 : 0);
        }
        return min(dp[n][0], dp[n][1]);
    }
};
int main() 
{
    
    Solution s;
    string s1 = "00110";
    cout << "minFlipsMonoIncr: " << s.minFlipsMonoIncr(s1) << endl;
}

The corresponding results

$ ./test
minFlipsMonoIncr: 1
原网站

版权声明
本文为[SUNNY_CHANGQI]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_38396940/article/details/125238573