您的位置:首页 > 其它

leetcode-20 Valid Parentheses

2016-03-25 16:47 363 查看
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.

栈实现括号匹配 (DFS)               

//////////////////////////////////////////////////////////////////////////
// start: character matching

bool isValid (string const& s)
{
    stack<char> chars;
    string left = "([{";
    string right = ")]}";

    for(auto ch: s)
    {
        if(left.find(ch) != string::npos)// 如果是左半部分则入栈,如果是右半部分,取出栈顶部分进行匹配
            chars.push(ch);
        else
        {
            if(chars.empty() || chars.top() != left[right.find(ch)])  // 如果栈中没有元素或者栈顶元素不匹配则失败
                return false;  // find函数可以返回下标
            else
                chars.pop();                
        }
    }
    return chars.empty();  // 如果栈中还有元素则也匹配失败
}              

// end
//////////////////////////////////////////////////////////////////////////
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: