zoukankan      html  css  js  c++  java
  • [LeetCode] 20. Valid Parentheses

    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.

    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
    

    思路是用栈,如果栈顶是(,下一个字符是),就把栈顶的(出栈,[{也是一样,最后看栈是否为空就行了

    bool isValid(string s)
    {
        stack<char> stk;
        for (char c : s)
        {
            if (stk.empty() || c == '(' || c == '[' || c == '{')
            {
                stk.push(c);
                continue;
            }
    
            char top = stk.top();
            if ((top == '(' && c == ')') ||
                (top == '[' && c == ']') ||
                (top == '{' && c == '}'))
            {
                stk.pop();
            }
            else
            {
                return false;
            }
        }
    
        return stk.empty();
    }
    

    看了下LeetCode上其他的代码,我觉得我的这个版本挺好的,就不介绍其他代码了,思路都是一样的

  • 相关阅读:
    注解
    LeedCode刷题:337.打家劫舍Ⅲ
    计蒜客:踏青(DFS)
    C++中memset()用法
    DFS深度优先搜索(附例题)
    计蒜客:网络交友:map+set+并查集
    JavaString类中valueOf和parseInt的区别
    Leedcode刷题 539. 最小时间差
    ps换衣服颜色
    hashmap的一些总结
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9455484.html
Copyright © 2011-2022 走看看