1963. Minimum Number of Swaps to Make the String Balanced - Medium 前往題目 想法 Stack? 思路這題可以一次換兩個,為一個swap 疊代所有字符 看到[就+1 看到]就判斷是否size大於0,-1 如此一來剩下的就換是錯位的括號有幾個了 Codeclass Solution { public int minSwaps(String s) { int sSize = 0; // Go through the string for (int i = 0; i < s.length(); ++i) { // Current character char ch = s.charAt(i); if (ch == '[') { ++sSize; } else { if (sSize > 0) --sSize; } } // Number of swap return (sSize + 1) / 2; } } Leetcode > Medium #Leetcode #心得 #Stack #String #Greedy #Two Pointers 1963. Minimum Number of Swaps to Make the String Balanced - Medium https://f88083.github.io/2024/05/23/1963-Minimum-Number-of-Swaps-to-Make-the-String-Balanced-Medium/ 作者 Simon Lai 發布於 2024年5月23日 許可協議 2483. Minimum Penalty for a Shop - Medium 上一篇 2002. Maximum Product of the Length of Two Palindromic Subsequences - Medium 下一篇 Please enable JavaScript to view the comments