Skip to content

Latest commit

 

History

History
66 lines (53 loc) · 1.54 KB

_921. Minimum Add to Make Parentheses Valid.md

File metadata and controls

66 lines (53 loc) · 1.54 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 12, 2024

Last updated : July 01, 2024


Related Topics : String, Stack, Greedy

Acceptance Rate : 74.61 %


Solutions

Java

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;
    }
}

Python

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