[LintCode] Valid Parentheses 验证括号

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

 
Example

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

LeetCode上的原题,请参见我之前的博客Valid Parentheses

class Solution {
public:
    /**
     * @param s A string
     * @return whether the string is a valid parentheses
     */
    bool isValidParentheses(string& s) {
        stack<char> st;
        for (char c : s) {
            if (c == ')' || c == '}' || c == ']') {
                if (st.empty()) return false;
                if (c == ')' && st.top() != '(') return false; 
                if (c == '}' && st.top() != '{') return false;
                if (c == ']' && st.top() != '[') return false;
                st.pop();
            } else {
                st.push(c);
            }
        }
        return st.empty();
    }
};
原文地址:https://www.cnblogs.com/grandyang/p/5709256.html