Given a string s of '('
, ')'
and lowercase English characters.
Your task is to remove the minimum number of parentheses ( '('
or ')'
, in any positions )
so that the resulting parentheses string is valid and return any valid string.
Formally, a parentheses string is valid if and only if:
- It is the empty string, contains only lowercase characters, or
- It can be written as
AB
(A concatenated with B), where A and B are valid strings, or - It can be written as
(A)
, where A is a valid string.
Test Cases
Example 1:
Input: s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.
Example 2:
Input: s = "))(("
Output: ""
Explanation: An empty string is also valid.
Solution
class Solution {
public:
string minRemoveToMakeValid(string s) {
stack<int> st;
int n = s.length();
for(int i=0; i<n; i++) {
if (s[i] == '(') {
st.push(i);
} else if (s[i] == ')') {
if (!st.empty()) {
st.pop();
} else {
s[i] = '*';
}
}
}
while(!st.empty()) {
s[st.top()] = '*';
st.pop();
}
s.erase(remove(s.begin(), s.end(), '*'), s.end());
return s;
}
};
class Solution {
public String minRemoveToMakeValid(String s) {
StringBuilder sb = new StringBuilder(s);
Stack<Integer> stack = new Stack<>();
int n = s.length();
for(int i=0; i<n; i++) {
if (s.charAt(i) == '(') stack.push(i);
else if (s.charAt(i) == ')') {
if (!stack.isEmpty()) stack.pop();
else sb.setCharAt(i, '*');
}
}
while(!stack.isEmpty()) {
sb.setCharAt(stack.pop(), '*');
}
return sb.toString().replace("*", "");
}
}
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
arr = list(s)
print(arr)
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
elif s[i] == ')':
if not stack:
arr[i] = '*'
else:
stack.pop()
while stack:
arr[stack.pop()] = '*'
return ''.join(arr).replace('*', '')