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();
    }
  • 相关阅读:
    为何与0xff进行与运算
    智能指针学习笔记
    linux下多线程编程
    redis源码分析之内存布局
    spring
    java
    程序员进修之路
    散列类型(hash)
    字符串类型
    Jmeter使用Websocket插件测试SingalR,外加还有阿里云PTS的Jmeter原生测试爬坑日志。
  • 原文地址:https://www.cnblogs.com/ww-jin/p/4404163.html
Copyright © 2011-2022 走看看