LC.P926[将字符串翻转到单调递增]

方法一:动态规划

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int minFlipsMonoIncr(String s) {
int n = s.length();
int dp0 = 0, dp1 = 0;
for (int i = 0; i < n; ++i) {
char c = s.charAt(i);
int dp0New = dp0 + (c == '1' ? 1 : 0);
int dp1New = Math.min(dp0, dp1) + (c == '0' ? 1 : 0);
dp0 = dp0New;
dp1 = dp1New;
}
return Math.min(dp0, dp1);
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$