1249. Minimum Remove to Make Valid Parentheses || Leetcode || Code + Explanation
Vložit
- čas přidán 18. 02. 2021
- 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.
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 = "a)b(c)d"
Output: "ab(c)d"
Example 3:
Input: s = "))(("
Output: ""
Explanation: An empty string is also valid.
Link to challenge: leetcode.com/problems/minimum... or
leetcode.com/explore/challeng...
Better than all present on CZcams
Thanks!!
Good explain mam
Thank you for such great explanation!!
super mam
Very well explained.
Great explanation❤
best explanation thank you
Thanks Alisha!!
Thanks a lot Ma'am
What is erase function???
Thanks dii
This approach will not work for )()(
import java.util.Stack;
class Solution {
public String minRemoveToMakeValid(String s) {
Stack stack = new Stack();
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == '(') {
stack.push(i);
} else if (sb.charAt(i) == ')') {
if (!stack.isEmpty() && sb.charAt(stack.peek()) == '(') {
stack.pop();
} else {
stack.push(i);
}
}
}
while (!stack.isEmpty()) {
int removeIndex = stack.pop();
sb.deleteCharAt(removeIndex);
}
return sb.toString();
}
}
Awesome