当前位置:网站首页>【926. 将字符串翻转到单调递增】
【926. 将字符串翻转到单调递增】
2022-06-12 09:58:00 【Sugar_wolf】
来源:力扣(LeetCode)
描述:
如果一个二进制字符串,是以一些 0(可能没有 0)后面跟着一些 1(也可能没有 1)的形式组成的,那么该字符串是 单调递增 的。
给你一个二进制字符串 s,你可以将任何 0 翻转为 1 或者将 1 翻转为 0 。
返回使 s 单调递增的最小翻转次数。
示例 1:
输入:s = "00110"
输出:1
解释:翻转最后一位得到 00111.
示例 2:
输入:s = "010110"
输出:2
解释:翻转得到 011111,或者是 000111。
示例 3:
输入:s = "00011000"
输出:2
解释:翻转得到 00000000。
提示:
- 1 <= s.length <= 105
- s[i] 为 ‘0’ 或 ‘1’
方法:动态规划


代码:
class Solution {
public:
int minFlipsMonoIncr(string &s) {
int dp0 = 0, dp1 = 0;
for (char c: s) {
int dp0New = dp0, dp1New = min(dp0, dp1);
if (c == '1') {
dp0New++;
} else {
dp1New++;
}
dp0 = dp0New;
dp1 = dp1New;
}
return min(dp0, dp1);
}
};
执行用时:16 ms, 在所有 C++ 提交中击败了96.07%的用户
内存消耗:10.8 MB, 在所有 C++ 提交中击败了73.81%的用户
复杂度分析
时间复杂度: O(n),其中 n 是字符串 s 的长度。需要遍历字符串一次,对于每个字符计算最小翻转次数的时间都是 O(1)。
空间复杂度: O(1)。使用空间优化的方法,空间复杂度是 O(1)。
author:LeetCode-Solution
边栏推荐
- The white paper "protecting our digital heritage: DNA data storage" was released
- 003:what does AWS think is a data lake?
- Why is cross-border e-commerce so popular? Papaya mobile takes you to find out
- Clickhouse column basic data type description
- 电阻的作用有哪些?(超全)
- HALCON联合C#检测表面缺陷——仿射变换(三)
- SAP Hana error message sys_ XSA authentication failed SQLSTATE - 28000
- [path of system analyst] Chapter 18 security analysis and design of double disk system
- C# break continue return 三者区别
- 优质好书助成长 猿辅导携四大出版社推荐“暑期好书”
猜你喜欢

markdown_图片并排的方案

SAP Hana error message sys_ XSA authentication failed SQLSTATE - 28000

QQ,微信能聊天都靠它(socket)?

Ceph性能优化与增强

CEPH performance optimization and enhancement

SAP Hana error message sys_ XSA authentication failed SQLSTATE - 28000

gnu-efi开发环境设置

《保护我们的数字遗产:DNA数据存储》白皮书发布

MYSQL的最左匹配原则的原理讲解

Shen Min, CIO of science and technology innovator Digital China Group: the best practice model is failing, and open source accelerates Distributed Innovation
随机推荐
Clickhouse column basic data type description
使用C语言代码实现工厂端LCD RGB的测试程序
2022 pole technology communication - anmou technology ushers in new opportunities for development
7-4 network red dot punch in strategy (DFS)
Auto.js学习笔记4:autojs打包后,大部分华为等大牌子手机无法安装?利用模拟器远程在autoPro里签名打包可以解决该问题。
Research progress of DNA digital information storage
SAP HANA 错误消息 SYS_XSA authentication failed SQLSTATE - 28000
Auto. JS debugging: use the network mode of lightning simulator for debugging
June training (day 12) - linked list
markdown_图片并排的方案
[path of system analyst] Chapter 18 security analysis and design of double disk system
Abstract classes and interfaces
Reading notes of the fifth cultivation
Using C language code to realize factory LCD RGB test program
[cloud native] what exactly does it mean? This article shares the answer with you
GNU EFI development environment settings
C 语言仅凭自学能到什么高度?
[cloud native] establishment of Eureka service registration
Auto.js学习笔记10:实例化自定义对象,在子线程使用JSON.stringify()方法导致报错(已解决)
Ceph性能优化与增强