其他分享
首页 > 其他分享> > 1541. Minimum Insertions to Balance a Parentheses String

1541. Minimum Insertions to Balance a Parentheses String

作者:互联网

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;
    }

 

标签:count,Parentheses,Insertions,String,res,stk,parentheses,right,stack
来源: https://www.cnblogs.com/feiflytech/p/15860022.html