Stack and String-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.

tips: 这里用了一个c++11的新特性 range-based for loop
class Solution {
public:
    bool isValid(string s) {
        stack stk;
        for(char c : s){
            if(c == '(' || c == '{' || c == '[')
                stk.push(c);
            else{
                if(stk.empty() || (c != stk.top()+1 && c != stk.top()+2))
                    return false;
                else
                    stk.pop();
            }
        }
        return stk.empty();
    }
};

你可能感兴趣的:(Stack and String-20. Valid Parentheses)