LeetCode[stack]: Valid Parentheses

来源:互联网 发布:创建wifi热点软件 编辑:程序博客网 时间:2024/05/21 22:29

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) {        stack<char> parentheses;        for (auto c : s) {            if (c == '(' || c == '{' || c == '[')                parentheses.push(c);            else {                if (parentheses.empty())                    return false;                else if (c == ')' && parentheses.top() != '(')                    return false;                else if (c == ']' && parentheses.top() != '[')                    return false;                else if (c == '}' && parentheses.top() != '{')                    return false;                parentheses.pop();            }        }        return parentheses.empty();    }


0 0