LeetCode:926. 将字符串翻转到单调递增
暴力法超时:思想:动态规划
public int minFlipsMonoIncrb(String S) { int result = S.length(); for (int i = 0; i < S.length(); i++) { char[] str1 = S.substring(0, i).toCharArray(); char[] str2 = S.substring(i + 1, S.length()).toCharArray(); int zero = 0; int one = 0; for (int j = 0; j < str1.length; j++) { if (str1[j] == '1') zero++; } for (int j = 0; j < str2.length; j++) { if (str2[j] == '0') one++; } int re = zero + one; if (re < result) result = re; } return result; }
优化后:
public int minFlipsMonoIncr(String S) { int result = S.length(); int zero = 0; int leftOne = 0; int rightZero = 0; for (int i = 0; i < S.length(); i++) { if (S.charAt(i) == '0') zero++; } rightZero = zero; for (int i = -1; i < S.length(); i++) { if (i == -1) { } else { if (S.charAt(i) == '0') { rightZero--; } if (S.charAt(i) == '1') { leftOne++; } } int re = leftOne + rightZero; if (re < result) result = re; } return result; }
微信搜索桔子科研或者扫描二维码,第一时间获取编程有趣的知识和最新科研学术成果。
![](https://images.cnblogs.com/cnblogs_com/godoforange/1390071/o_211204035711_qrcode_for_gh_7f100002de19_344.jpg)