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上其他的代码,我觉得我的这个版本挺好的,就不介绍其他代码了,思路都是一样的

  • 相关阅读:
    python+hadoop=?
    Fluentd: The Missing Log Collector
    hadoop streaming 记录
    valgrind备忘
    [hadoop源码阅读][9]mapreduce概论
    GNU Binutils工具
    vim encoding
    [hadoop源码阅读][8]datanodedatanode
    Webdis: HTTP + JSON API for Redis
    gdb 小备注
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9455484.html
Copyright © 2011-2022 走看看