`

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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics