当前位置:网站首页>926. 将字符串翻转到单调递增
926. 将字符串翻转到单调递增
2022-06-11 22:16:00 【彼淇梁】
926. 将字符串翻转到单调递增【中等题】【每日一题】
思路:
【动态规划】
参考官解代码,并将解题思路写在注释里。
代码:
class Solution {
public int minFlipsMonoIncr(String s) {
int n = s.length();
//dp0和dp1分别表示当前下标i对应的字符翻转为0和1的情况下,使子串[0,i]递增的最小翻转次数,初值均为0
int dp0 = 0,dp1 = 0;
for (int i = 0; i < n; i++) {
//dp1的含义是,将i位置字符翻转为1时,保证子串[0,i]递增的最小翻转次数,但将i位置翻转为1有两种情况:i-1位置为 0 或者 为1
//因此,为了保证翻转次数最小,将dp1更新为dp0和dp1的较小值
dp1 = Math.min(dp0,dp1);
//取出当前下标i位置的字符
char c = s.charAt(i);
//如果当前实际字符是1,那么将其翻转为0后,dp0++,将其翻转为1后,dp1不变
if (c == '1'){
dp0++;
}else {
//如果当前实际字符是0,那么将其翻转为0,dp0不变,将其翻转为1,dp1++
dp1++;
}
}
//此时的dp0和dp1表示的是 将字符串s最后一个字符翻转为0或者翻转为1,使得整个子串保持递增的最小累计翻转次数,返回两者之间的较小值即可
return Math.min(dp0,dp1);
}
}
边栏推荐
- Study notes of mattlotlib and Tkinter (I)
- 二叉树的基本操作与题型总结
- 剑指offer数组题型总结篇
- Sword finger offer array question type summary
- 消息队列入门MQ
- C language implements eight sorts (3)
- 电脑强制关机 oracle登录不上
- Unity3d getlaunchintintforpackage getting package returned null
- Two methods to judge the storage of large and small end
- Submit task to thread pool
猜你喜欢

Matlab: solution of folder locking problem

Win10弹出USB时出现该设备正在使用的解决方法

仅需三步学会使用低代码ThingJS与森数据DIX数据对接

什么是死锁?(把死锁给大家讲明白,知道是什么,为什么用,怎么用)

二叉树的基本操作与题型总结
![[academic related] under the application review system, how difficult is it to study for a doctoral degree in a double first-class university?](/img/cd/e7ffecbee13596f2298ee8c0a5b873.jpg)
[academic related] under the application review system, how difficult is it to study for a doctoral degree in a double first-class university?

Internet of things development practice 18 scenario linkage: how does an intelligent light perceive light? (I) (learning notes)

Superscalar processor design yaoyongbin Chapter 2 cache -- Excerpt from subsection 2.2

Huawei equipment configuration h-vpn

超标量处理器设计 姚永斌 第2章 Cache --2.3 小节摘录
随机推荐
Leetcode stack topic summary
Tkinter study notes (III)
leetcode 中的位运算
Static PVC with CEPH CSI
打印机无法打印测试页是什么原因
Huawei equipment configuration hovpn
Implementation of sequencelist sequence table
Win10弹出USB时出现该设备正在使用的解决方法
Use the securecrtportable script function to read data from network devices
【LeetCode】11. Container with the most water
On the night of the joint commissioning, I beat up my colleagues
Simple example of logistic regression for machine learning
Go OS module
R语言书籍学习03 《深入浅出R语言数据分析》-第十章 关联规则 第十一章 随机森林
重温c语言一
67. binary sum
Prefabricated dishes in the trillion market have also begun to roll inside. How can brands stand out in the fierce competition?
R language book learning 03 "in simple terms R language data analysis" - Chapter 8 logistic regression model Chapter 9 clustering model
消息队列入门MQ
电脑强制关机 oracle登录不上