这道题是典型的括号题,一般来说,括号题用stack做,但是这道题因为太简单了,连stack都不用, 就用int就好了,时间复杂度O(n)。

    public int minAddToMakeValid(String s) {
        int count = 0;
        int res = 0;
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(c=='('){
                count++;
            }else if(c==')'){
                if(count>0)
                    count--;  //count means left parenthesis needed.
                else
                    res++;  //res means right parenthesis needed.
            }
        }
        return res + count;
    }

 

posted on 2022-01-28 04:31  阳光明媚的菲越  阅读(18)  评论(0编辑  收藏  举报