• C# 写 LeetCode easy #20 Valid Parentheses


    20、Valid Parentheses

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

    An input string is valid if:

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

    Note that an empty string is also considered valid.

    Example 1:

    Input: "()"
    Output: true
    

    Example 2:

    Input: "()[]{}"
    Output: true
    

    Example 3:

    Input: "(]"
    Output: false
    

    Example 4:

    Input: "([)]"
    Output: false
    

    Example 5:

    Input: "{[]}"
    Output: true

    代码:
    static void Main(string[] args)
    {
        string str = "({}[])";
        bool res = IsValid(str);
        Console.WriteLine(res);
        Console.ReadKey();
    }
    
    private static bool IsValid(string s)
    {
        if (s.Length % 2 != 0) return false;
        Dictionary<char, char> dic = new Dictionary<char, char>() {
                    { ')','('},
                    { ']','['},
                    { '}','{'}
                };
        var stack = new Stack<char>();
        foreach (var str in s)
        {
            if (dic.ContainsKey(str))
            {
                if (stack.Count != 0 && stack.Peek() == dic[str])
                {
                    stack.Pop();
                }
                else
                {
                    return false;
                }
            }
            else
            {
                stack.Push(str);
            }
        }
        return stack.Count == 0;
    }

    解析:

    输入:字符串

    输出:bool类型

    思想

      首先,这种匹配问题,都放在栈中,栈特点是先进后出。这里以键值对的形式把匹配项存入字典中。另外奇数个字符是不对的。

      其次,刚开始栈空,将向右方向的字符((,{,[)全部存入栈中,然后若出现一个向左方向的,就在栈中匹配,判断是否与栈顶元素匹配。若匹配,则移出。否则返回false。

      最后,判断栈中是否将全部元素匹配完毕,即都被移出,返回bool结果。

    时间复杂度:O(n)

     
  • 相关阅读:
    高德车载导航自研图片格式的探索和实践
    导航定位向高精定位的演进与实践
    高德算法工程一体化实践和思考
    机器学习在高德用户反馈信息处理中的实践
    UI自动化技术在高德的实践
    高德网络定位算法的演进
    系统重构的道与术
    基于深度学习的图像分割在高德的实践
    MySQL索引那些事
    如何优雅的将Mybatis日志中的Preparing与Parameters转换为可执行SQL
  • 原文地址:https://www.cnblogs.com/s-c-x/p/10038446.html
Copyright © 2020-2023  润新知