码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode【20】Valid Parentheses

时间:2015-04-08 23:19:09      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

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();
}

 

LeetCode【20】Valid Parentheses

标签:

原文地址:http://www.cnblogs.com/ww-jin/p/4404163.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!