Skip to content
本页目录

0020-有效的括号

https://leetcode.cn/problems/valid-parentheses

给定一个只包括 '(',')','{','}','[',']'的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。

示例 1:

输入:s = "()"
输出:true

示例2:

输入:s = "()[]{}"
输出:true

示例3:

输入:s = "(]"
输出:false

示例4:

输入:s = "([)]"
输出:false

示例5:

输入:s = "{[]}"
输出:true

提示:

1 <= s.length <= 104
s 仅由括号 '()[]{}' 组成

思路

使用栈,遇到左括号就压栈,遇到右括号就出栈比较,如果不相等就返回false 最后检测栈的个数,如果不为0则返回false

参考代码

csharp
public class Solution {
    public bool IsValid(string s) {
    	Stack<char> stack = new Stack<char>();
    	for(int i=0;i<s.Length;i++){
    		if(s[i] == '(' || s[i] == '{' || s[i] == '['){
    			stack.Push(s[i]);
    		}
    		else{
                if(stack.Count > 0){
                    char c = stack.Peek();
                    char r = s[i]; 
                    if(c == '(' && r == ')' || c == '[' && r==']' || c == '{' && r == '}'){
                        stack.Pop();
                    }
                    else{
                        return false;
                    }
                }
                else{
                    return false;
                }                
    		}
    	}
    	return stack.Count == 0;
    }
}

参考代码2,括号可以用 Dictionary 缓存

其中判断的时候,也直接 dict[stack.Pop()] == s[i] 注意:添加进入的是对称的括号

csharp
public class Solution {
    public bool IsValid(string s) {
        Stack<char> stack = new Stack<char>();
        Dictionary<char,char> dict = new Dictionary<char,char>();
        dict.Add('(',')');
        dict.Add('[',']');
        dict.Add('{','}');
        for(int i=0;i<s.Length;i++){
            if(s[i] == '(' || s[i] == '{' || s[i] == '['){
                stack.Push(s[i]);
            }
            else{
                if(stack.Count > 0 && dict[stack.Peek()] == s[i]){
                    stack.Pop();
                }
                else{
                    return false;
                }                
            }
        }
        return stack.Count == 0;
    }
}

Released under the MIT License.