921. Minimum Add to Make Parentheses Valid
/**
* Problem: LeetCode 921 - Minimum Add to Make Parentheses Valid
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int minAddToMakeValid(String s) {
int open = 0; // unmatched '('
int add = 0; // unmatched ')'
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
open++;
} else {
if (open > 0) {
open--;
} else {
add++;
}
}
}
return add + open;
}
}
"""
Problem: LeetCode 921 - Minimum Add to Make Parentheses Valid
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
class Solution:
def minAddToMakeValid(self, s: str) -> int:
open_count = 0 # unmatched '('
add = 0 # unmatched ')'
for c in s:
if c == '(':
open_count += 1
else:
if open_count > 0:
open_count -= 1
else:
add += 1
return add + open_count
/**
* Problem: LeetCode 921 - Minimum Add to Make Parentheses Valid
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <string>
using namespace std;
/**
* Problem: LeetCode 921 - Minimum Add to Make Parentheses Valid
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
int minAddToMakeValid(string s) {
int open = 0; // unmatched '('
int add = 0; // unmatched ')'
for (char c : s) {
if (c == '(') {
open++;
} else {
if (open > 0) {
open--;
} else {
add++;
}
}
}
return add + open;
}
};
/**
* Problem: LeetCode 921 - Minimum Add to Make Parentheses Valid
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
var minAddToMakeValid = function(s) {
let open = 0; // unmatched '('
let add = 0; // unmatched ')'
for (let i = 0; i < s.length; i++) {
if (s[i] === '(') {
open++;
} else {
if (open > 0) {
open--;
} else {
add++;
}
}
}
return add + open;
};