-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
minimum remove to make valid parenteses
- Loading branch information
1 parent
b1641a9
commit 5aed3b1
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
""" | ||
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. | ||
""" | ||
|
||
|
||
class Solution: | ||
def minRemoveToMakeValid(self, S: str) -> str: | ||
S, stack = list(S), [] | ||
for i, c in enumerate(S): | ||
if c == ")": | ||
if stack: | ||
stack.pop() | ||
else: | ||
S[i] = "" | ||
elif c == "(": | ||
stack.append(i) | ||
for i in stack: | ||
S[i] = "" | ||
return "".join(S) |