publicclassLC1541{ publicstaticintminInsertions(String s){ int i = 0; Stack<String> Left = new Stack<>(); Stack<String> Right2 = new Stack<>(); int rightDemand = 0; int leftDemand = 0;
while (i < s.length()) { if (s.charAt(i) == '(') { Left.push("("); } else { if (i + 1 < s.length() && s.charAt(i + 1) == ')') { // try to combine "))" i += 1; // skip 1 if (!Left.empty()) { Left.pop(); } else { Right2.push("))"); } } else { if (!Left.empty()) { // Add ")" to the right immediately and eliminate one left. Left.pop(); rightDemand++; } else { // only one single ')', immediately eliminate it leftDemand += 1; rightDemand += 1; } } } i++; }