zoukankan      html  css  js  c++  java
  • 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)

     
  • 相关阅读:
    无法添加sql server ER图
    我和COC
    WordPress怎样设置菜单栏旋转小图标
    VS Code怎样设置成中文
    初探 Git Submodules
    使用 rsync-deploy-action 同步 Hexo 博客到个人服务器
    Latex基本语法简记
    SQLAlchemy建立数据库模型之间的关系
    Flask的请求钩子与上下文简览
    如何将本地项目推送到Github
  • 原文地址:https://www.cnblogs.com/s-c-x/p/10038446.html
Copyright © 2011-2022 走看看