LeetCode 20. 有效的括号 (C#实现)——栈

问题:https://leetcode-cn.com/problems/valid-parentheses/

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

有效字符串需满足:

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

注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

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

示例 3:

输入: "(]"
输出: false

示例 4:

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

示例 5:

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

GitHub实现:https://github.com/JonathanZxxxx/LeetCode/blob/master/ValidParentheses.cs

Blog:https://www.cnblogs.com/zxxxx/

思路:利用栈后进先出的特性,扫描字符串,如果是左括号入栈,如果是右括号,判断栈第一个元素是否匹配,注意栈为空的情况;利用字典即可匹配左右括号

        public bool IsValid(string s)
        {
            var map = new Dictionary<char, char>
            {
                { '}', '{' },
                { ']', '[' },
                { ')', '(' }
            };
            var sChar = s.ToCharArray();
            var stack = new Stack<char>();
            for (int i = 0; i < s.Length; i++)
            {
                var c = sChar[i];
                if (map.ContainsKey(c))
                {
                    var top = stack.Any() ? stack.Pop() : '#';
                    if (top != map[c])
                    {
                        return false;
                    }
                }
                else
                {
                    stack.Push(c);
                }
            }
            return !stack.Any();
        }
原文地址:https://www.cnblogs.com/zxxxx/p/10521332.html