LeetCode:926. 将字符串翻转到单调递增
Posted godoforange
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; }
以上是关于LeetCode:926. 将字符串翻转到单调递增的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 926. Flip String to Monotone Increasing (将字符串翻转到单调递增)
Leetcode-926 Flip String to Monotone Increasing(将字符串翻转到单调递增)
[LeetCode] 926. Flip String to Monotone Increasing 翻转字符串到单调递增