Skip to content
本页目录

1249-移除无效的括号

https://leetcode.cn/problems/minimum-remove-to-make-valid-parentheses

给你一个由 '('、')' 和小写字母组成的字符串 s。 你需要从字符串中删除最少数目的 '(' 或者 ')' (可以删除任意位置的括号),使得剩下的「括号字符串」有效。 请返回任意一个合法字符串。 有效「括号字符串」应当符合以下 任意一条 要求: 空字符串或只包含小写字母的字符串 可以被写作 AB(A 连接 B)的字符串,其中 A 和 B 都是有效「括号字符串」 可以被写作 (A) 的字符串,其中 A 是一个有效的「括号字符串」

示例 1:

输入:s = "lee(t(c)o)de)"
输出:"lee(t(c)o)de"
解释:"lee(t(co)de)" , "lee(t(c)ode)" 也是一个可行答案。

示例 2:

输入:s = "a)b(c)d"
输出:"ab(c)d"

示例 3:

输入:s = "))(("
输出:""
解释:空字符串也是有效的

示例 4:

输入:s = "(a(b(c)d)"
输出:"a(b(c)d)"

提示:

1 <= s.length <= 10^5
s[i] 可能是 '('、')' 或英文小写字母

思路【ME】

  1. 将字符串转换为字符数组方便操作
  2. 因为左括号开始才是合法的,设置 leftCount 表示左括号的个数
  3. 遍历,遇到左括号 leftCount++
  4. 如果遇到右括号,且 leftCount == 0,则直接置为空,否则 leftCount - 1 注意:上述操作判断了左括号,需要从右括号在判断一次,才能删除多余的左括号

参考代码

csharp
public class Solution {
    public string MinRemoveToMakeValid(string s) {
    	char[] strs = s.ToCharArray();
    	int leftCount = 0;
    	int rightCount = 0;
    	//从左往右
    	for(int i=0; i < strs.Length; i++){
    		if(strs[i] == '('){
    			leftCount++;
    		}
    		else if(strs[i] == ')'){
    			if(leftCount > 0){
    				leftCount--;
    			}
    			else{
    				strs[i] = ' ';
    			}
    		}
    	}
    	//从右往左
    	for(int i = strs.Length -1; i>=0; i--){
    		if(strs[i] == ')'){
    			rightCount++;
    		}
    		else if(strs[i] == '('){
    			if(rightCount > 0){
    				rightCount--;
    			}
    			else{
    				strs[i] = ' ';
    			}
    		}
    	}
    	//输出
    	StringBuilder sb = new StringBuilder();
    	for(int i=0;i<strs.Length;i++){
    		if(strs[i] != ' '){
    			sb.Append(strs[i].ToString());
    		}
    	}
    	return sb.ToString();
    }
}

Released under the MIT License.