精華區beta Marginalman 關於我們 聯絡資訊
https://leetcode.com/problems/maximum-score-after-splitting-a-string/description 1422. Maximum Score After Splitting a String 給你一個字串s,我們將s分成左右兩個子字串,定義分數為左邊0的個數加上右邊1的個數 求出一種切法可以得到的最高分數。 思路: 1.先算出1的總數,然後從左邊開始算0的數量並把1的數量減少就可以遍歷兩次就獲得每 種切法的左邊0和右邊1的數量,取最大即可。 Java Code ------------------------------------------- class Solution { public int maxScore(String s) { int res = 0; int one = 0; int zero = 0; for (char ch : s.toCharArray()) { if (ch == '1') { one++; } } for (int i = 0; i < s.length() - 1; i++) { if (s.charAt(i) == '0') { zero++; } else { one--; } res = Math.max(res, one + zero); } return res; } } ------------------------------------------- -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.73.13 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1703229953.A.CFE.html