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.

class Solution{
public:
    bool isValid(string str){
        stack<char> S;
        for(auto c: str){
            switch(c){
                case '(': case '[': case '{': S.push(c);
                break;
                case ')': if(!S.size() || S.top() != '(') return false;
                          else S.pop();
                break;
                case ']': if(!S.size() || S.top() != '[') return false;
                          else S.pop();
                break;
                case '}': if(!S.size() || S.top() != '{') return false;
                          else S.pop();
                break;
                default : return false;
            }
        }
        return !S.size();
    }
};

 

posted @ 2018-03-17 22:48  Pretty9  阅读(153)  评论(0编辑  收藏  举报