这道题是典型的括号题,一般来说,括号题用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; }