博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

LeetCode【20】Valid Parentheses

Posted on 2015-04-08 21:52  NUST小文  阅读(99)  评论(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();
}