C#LeetCode刷题之#20-有效的括号(Valid Parentheses)

问题

 

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4018 访问。

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

有效字符串需满足:

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

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

输入: "()"

输出: true

输入: "()[]{}"

输出: true

输入: "(]"

输出: false

输入: "([)]"

输出: false

输入: "{[]}"

输出: true


Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  • Open brackets must be closed by the same type of brackets.
  • Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Input: "()"

Output: true

Input: "()[]{}"

Output: true

Input: "(]"

Output: false

Input: "([)]"

Output: false

Input: "{[]}"

Output: true


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4018 访问。

public class Program {

    public static void Main(string[] args) {
        var s = "{[]}";

        var res = IsValid(s);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static bool IsValid(string s) {
        //括号的匹配问题基本都是使用栈来解决的
        //如果是奇数,肯定不匹配
        if(s.Length % 2 != 0) return false;
        //用一个字典增加代码的可读性和可扩展性
        var dic = new Dictionary<char, char>() {
            {')' , '('},
            {']' , '['},
            {'}' , '{'}
        };
        //用栈,遇到左括号压入栈,遇到右括号删除栈顶与之匹配的左括号
        var stack = new Stack<char>();
        foreach(var c in s) {
            //发现是一个右括号
            if(dic.ContainsKey(c)) {
                //若栈不为空,并且栈顶括号相匹配
                if(stack.Count != 0 && stack.Peek() == dic[c]) {
                    //弹出栈顶元素
                    stack.Pop();
                } else {
                    //若不匹配,立刻返回false
                    return false;
                }
            } else {
                //发现是一个左括号,压入栈
                stack.Push(c);
            }
        }
        //栈空表示完全匹配
        return stack.Count == 0;
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4018 访问。

True

分析:

显而易见,以上算法的时间复杂度为: O(n)

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值