[Leetcode][1249. Minimum Remove to Make Valid Parentheses] Stack Solution with Easy Detailed Explanation
By Long Luo
This article is the solution Stack Solution with Easy Detailed Explanation of Problem 1249. Minimum Remove to Make Valid Parentheses.
Intuition
First we can use Brute Force to into a two-step` algorithm:
- find all the \((\) and \()\) and get their indices;
- determine the indices that need to be deleted;
- creates a new string from the index of the deleted characters.
We can use a Stack to record the indices of all \((\) and \()\) s. When scanning to the end of the string, all indices remaining in the Stack are \((\) and \()\) s that do not match.
We also need to use a \(\texttt{Set}\) to keep track of unmatched \((\) and \()\) s. Then Delete each character that needs to be deleted according to the indices, and return the recreated string.
The code is as follows:
1 | public String minRemoveToMakeValid(String s) { |
Analysis
- Time Complexity: \(O(N)\).
- Space Complexity: \(O(N)\).
All suggestions are welcome. If you have any query or suggestion please comment below. Please upvote👍 if you like💗 it. Thank you:-)
Explore More Leetcode Solutions. 😉😃💗