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 withB
), whereA
andB
are valid strings, or - It can be written as
(A)
, whereA
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.Example 4:
Input: s = "(a(b(c)d)" Output: "a(b(c)d)"
移除无效的括号。
给你一个由 '('、')' 和小写字母组成的字符串 s。
你需要从字符串中删除最少数目的 '(' 或者 ')' (可以删除任意位置的括号),使得剩下的「括号字符串」有效。
请返回任意一个合法字符串。
有效「括号字符串」应当符合以下 任意一条 要求:
空字符串或只包含小写字母的字符串
可以被写作 AB(A 连接 B)的字符串,其中 A 和 B 都是有效「括号字符串」
可以被写作 (A) 的字符串,其中 A 是一个有效的「括号字符串」来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-remove-to-make-valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是stack但是这个题跟20题valid parenthesis还不太一样,因为不光是判断,而是最后需要返回一个有效的结果。这个题我没有用到stack但是用到了stack的思想,用一个open变量判断到底是左括号多还是右括号多,如果open小于0(右括号多)就一定不要再放右括号了。第一次扫描input,从左往右,append其他字符的同时,注意不要多append右括号即可;第二次从右往左scan第一次的结果,但是因为第一次扫描的时候只是控制不能让右括号多于左括号,这时有可能左括号是有多余的,所以在第二次从右往左扫描的时候需要判断如果左括号多了,就不要再加入结果集了。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public String minRemoveToMakeValid(String s) { 3 StringBuilder sb = new StringBuilder(); 4 int open = 0; 5 for (char c : s.toCharArray()) { 6 if (c == '(') { 7 open++; 8 } else if (c == ')') { 9 if (open == 0) { 10 continue; 11 } 12 open--; 13 } 14 sb.append(c); 15 } 16 17 StringBuilder res = new StringBuilder(); 18 for (int i = sb.length() - 1; i >= 0; i--) { 19 if (sb.charAt(i) == '(' && open-- > 0) { 20 continue; 21 } 22 res.append(sb.charAt(i)); 23 } 24 return res.reverse().toString(); 25 } 26 }