魔法师 (@Constanline) 在 Leetcode每日一题 —— 1541. 平衡括号字符串的最少插入次数 中发帖

思路
遍历字符串,按情况处理: 

左括号且有单独右括号。补上右括号,深度+2;() (
左括号且无单独右括号。深度+2;()) (
右括号且有深度。深度-1;() )
右括号且无深度。补上左括号,深度+1;)

代码
class Solution {
    public int minInsertions(String s) {
        int deep = 0;
        int ans = 0;
        for (char chr : s.toCharArray()) {
            if (chr == '(') {
                if ((deep & 1) == 1) {
                    deep--;
                    ans++;
                }
  ...
 
 
Back to Top