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.

    The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

    题目比较简单,一看就知道对栈的考查。不多说,上代码。

    bool isValid(string s)
    {
        if(s.empty())
            return true;
        if(s.size()%2 == 1)
            return false;
        stack<char> st;
        for(int i =0;i<s.size();i++)
        {
            char tmp=s[i];
            if(tmp=='(' || tmp=='[' || tmp=='{' )
            {
                st.push(tmp);
            }
            else
            {
                if(st.empty())
                    return false;
                if( (tmp==')'&&st.top()=='(') ||
                    (tmp==']'&&st.top()=='[') ||
                    (tmp=='}'&&st.top()=='{')
                    )
                    st.pop();
                else
                    return false;
            }
            if(st.empty())
                return true;
        }
    }

    再看别人写的,利用自动变量,鲁棒性比较好,代码比较精炼。

    bool isValid(string s)
    {
        string left = "([{", right = ")]}";  
        stack<char> stk;
        for (auto c : s) {
            if (left.find(c) != string::npos) {
                stk.push(c);
            }
            else {
                if (stk.empty() || stk.top() != left[right.find(c)])
                    return false;
                else
                    stk.pop();
            }
        }
        return stk.empty();
    }
  • 相关阅读:
    换教室
    [国家集训队]礼物
    【模板】扩展卢卡斯(学习笔记)
    Desert King
    绿豆蛙的归宿
    Dropping tests
    [SDOI2013]随机数生成器
    佳佳的fib
    [USACO10OPEN]水滑梯Water Slides
    强大的XML
  • 原文地址:https://www.cnblogs.com/ww-jin/p/4404163.html
Copyright © 2011-2022 走看看