Problem
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(Aconcatenated withB), whereAandBare valid strings, or - It can be written as
(A), whereAis a valid string.
Example 1:
1 | Input: s = "lee(t(c)o)de)" |
Example 2:
1 | Input: s = "a)b(c)d" |
Example 3:
1 | Input: s = "))((" |
Example 4:
1 | Input: s = "(a(b(c)d)" |
Constraints:
1 <= s.length <= 10^5s[i]is one of'(',')'and lowercase English letters.
Analysis
题目给出一个包含字符、(和)的字符串,要求我们通过移除尽可能少的括号,使得这个字符串是valid,对valid的定义就是括号匹配。所以题目的关键就是对括号的处理,遇到字母直接保留就可以了。这里和括号匹配的题目有点类似,但是其实并没有这么复杂,因为这里只有一种类型的括号,所以并不需要用到栈。
我们先来想invalid的情况有哪些,无非就是三种:
(比)多;)比(多;- 两个数量相等但是出现的顺序不对。
所以我们可以先从左到右遍历一遍,统计(出现的次数,遇到)就减1,如果(次数为0,说明)数量多出来了,这个时候就需要remove掉;然后再从右往左遍历,这个(次数为0,说明(数量多出来了,这个时候同样也要remove掉。
Solution
无
Code
1 | class Solution { |
Summary
这道题目的解法展示了一种很常见的解题思路,从两个方向各遍历一遍,这种做法用于计算某数字或字符的出现次数是非常有效的。这道题目的分享到这里,谢谢您的支持!