Skip to content

Commit d97f8aa

Browse files
Aaron LiuAaron Liu
authored andcommitted
update
1 parent f0dfc03 commit d97f8aa

File tree

1 file changed

+113
-0
lines changed

1 file changed

+113
-0
lines changed
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
'''
2+
Given a string s of '(' , ')' and lowercase English characters.
3+
4+
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.
5+
6+
Formally, a parentheses string is valid if and only if:
7+
8+
It is the empty string, contains only lowercase characters, or
9+
It can be written as AB (A concatenated with B), where A and B are valid strings, or
10+
It can be written as (A), where A is a valid string.
11+
12+
Example 1:
13+
14+
Input: s = "lee(t(c)o)de)"
15+
Output: "lee(t(c)o)de"
16+
Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.
17+
'''
18+
19+
'''
20+
solution 1: two pass
21+
只有左右括号匹配 才算balanced
22+
first pass to count number of '('
23+
second pass:
24+
遍历过程中 记录左括号个数left. 当前字符char 分类讨论:
25+
1. char == ')'.
26+
- if left>0 -> 左边有对应的匹配. char加入ret, left--.
27+
- else 左边没有‘(’与之匹配. right-- 避免右边的'('跟自己匹配.
28+
2. char == '('.
29+
-
30+
31+
'''
32+
33+
def minRemoveToMakeValid0(s: str) -> str:
34+
if not s:
35+
return ""
36+
37+
right = 0
38+
for char in s:
39+
if char == ')':
40+
right += 1
41+
42+
ret = []
43+
left = 0
44+
for char in s:
45+
if char == ')':
46+
if left > 0:
47+
ret.append(char)
48+
left -= 1 # 与当前')'配对
49+
else:
50+
right -= 1 # 防止与后面的'('配对
51+
elif char == '(':
52+
if right > 0:
53+
ret.append(char)
54+
left += 1 # 必须+=1
55+
right -= 1 # 与当前的配对
56+
else:
57+
ret.append(char)
58+
return "".join(ret)
59+
60+
61+
# Pass 1: Remove all invalid ")"
62+
first_pass_chars = []
63+
balance = 0
64+
open_seen = 0
65+
for c in s:
66+
if c == "(":
67+
balance += 1
68+
open_seen += 1
69+
if c == ")":
70+
if balance == 0:
71+
continue
72+
balance -= 1
73+
first_pass_chars.append(c)
74+
75+
# Pass 2: Remove the rightmost "("
76+
result = []
77+
open_to_keep = open_seen - balance
78+
for c in first_pass_chars:
79+
if c == "(":
80+
open_to_keep -= 1
81+
if open_to_keep < 0:
82+
continue
83+
result.append(c)
84+
85+
return "".join(result)
86+
87+
88+
def minRemoveToMakeValid1(self, s: str) -> str:
89+
# Pass 1: Remove all invalid ")"
90+
first_pass_chars = []
91+
balance = 0
92+
open_seen = 0
93+
for c in s:
94+
if c == "(":
95+
balance += 1
96+
open_seen += 1
97+
if c == ")":
98+
if balance == 0:
99+
continue
100+
balance -= 1
101+
first_pass_chars.append(c)
102+
103+
# Pass 2: Remove the rightmost "("
104+
result = []
105+
open_to_keep = open_seen - balance
106+
for c in first_pass_chars:
107+
if c == "(":
108+
open_to_keep -= 1
109+
if open_to_keep < 0:
110+
continue
111+
result.append(c)
112+
113+
return "".join(result)

0 commit comments

Comments
 (0)