LeetCode 20 - Valid Parentheses

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> st;
    for(char c : s) {
        if(!st.empty() && (c-st.top() == 1 || c-st.top() == 2)) {
            st.pop(); // )-(=1, ]-[=2, }-{=2
        } else {
            st.push(c);
        }
    }
    return st.empty();
}

 

你可能感兴趣的:(LeetCode)