All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : June 12, 2024
Last updated : July 01, 2024
Related Topics : String, Stack, Greedy
Acceptance Rate : 74.61 %
class Solution {
public int minAddToMakeValid(String s) {
Stack<Boolean> stk = new Stack<>();
int counter = 0;
for (Character c : s.toCharArray()) {
if (c == '(') {
stk.push(true);
} else if (stk.size() > 0 && stk.peek()) {
stk.pop();
} else {
counter++;
}
}
counter += stk.size();
return counter;
}
}
class Solution:
def minAddToMakeValid(self, s: str) -> int:
brackets = []
counter = 0
for c in s :
if c == '(' :
brackets.append(True)
elif len(brackets) > 0 and brackets[-1] :
brackets.pop()
else :
counter += 1
counter += len(brackets)
return counter