Parentheses的题,首先想到stack,思路如下:

1. If get a left parentheses, if the stack size is odd number, that means, one right parentheses is missing, so result plus one, and pop the missing right parentheses. And then, push two right parentheses to stack, that means, two right parentheses are need to keep balance.

2. If get a right parentheses, if the stack is empty, that means, one left parentheses is missing, so result plus one, but we need need one right parentheses to keep balance, so push the right parentheses to the stack. Otherwise, just pop the current parentheses is fine.

3. If there are still something left in stack, that means we still need some right parentheses to keep balance.

    public int minInsertions(String s) {
        int res = 0;
        Stack<Character> stk = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(') {
                if (stk.size() % 2 == 1) {
                    res++;
                    stk.pop();
                }
                stk.push(')');
                stk.push(')');
            } else {
                if (stk.isEmpty()) {
                    res += 1;
                    stk.push(')');
                } else {
                    stk.pop();
                }
            }
        }
        res += stk.size();
        return res;
    }

Observe the above solution, the stack actually can be replaced with a count, that count is the number of right parentheses needed:

    public int minInsertions(String s) {
        int res = 0;
        int count = 0;

        for (char c : s.toCharArray()) {
            if (c == '(') {
                if (count % 2 == 1) {
                    res++;
                    count--;
                }
                count += 2;
            } else {
                if (count == 0) {
                    res += 1;
                    count++;
                } else {
                    count--;
                }
            }
        }
        res += count;
        return res;
    }

 

posted on 2022-02-02 04:33  阳光明媚的菲越  阅读(20)  评论(0编辑  收藏  举报