1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public int minAddToMakeValid(String S) { char c1 = '('; char c2 = ')'; Stack<Character> stack = new Stack<>(); for (int i = 0; i < S.length(); i++) { char chr = S.charAt(i); if (stack.empty()) { stack.push(chr); }else { if (chr == c2 && stack.peek() == c1 ) { stack.pop(); }else { stack.push(chr); } } } return stack.size(); } }
|