且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LintCode] Valid Parentheses 验证括号

更新时间:2022-09-16 09:12:27

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.

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

本文转自博客园Grandyang的博客,原文链接:验证括号[LintCode] Valid Parentheses ,如需转载请自行联系原博主。