0
点赞
收藏
分享

微信扫一扫

921. 使括号有效的最少添加 栈

爱动漫建模 2022-04-27 阅读 42
// "(" 进栈
// ")" 两种情况: 栈为空, 所以必须加个"("
// 栈不为空, 是否匹配的上

class Solution {

    public boolean match(char a, char b) {
        if (a == '(' && b == ')')
            return true;
        return false;
    }

    public int minAddToMakeValid(String s) {
        ArrayDeque<Character> stack = new ArrayDeque<>();
        int cnt = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                stack.addLast(s.charAt(i));
            }else {
                if (stack.isEmpty()){
                    cnt++;
                    continue;
                }
                char c = stack.pollLast();
                if (!match(c, s.charAt(i))) {
                    cnt += 2;
                }
            }
        }
        if (!stack.isEmpty())
            cnt += stack.size();
        return cnt;
    }
}
举报

相关推荐

0 条评论