[LeetCode20]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 s) {
        stack<char> vec;
        for(char c : s)
        {
            switch(c)
            {
            case '(':
            case '[':
            case '{':
                vec.push(c);
                break;
            case ')':
                if(vec.empty() || vec.top() != '(')
                    return false;
                else
                    vec.pop();
                break;
            case ']':
                if(vec.empty() || vec.top() != '[')
                    return false;
                else
                    vec.pop();
                break;
            case '}':
                if(vec.empty() || vec.top() != '{')
                    return false;
                else
                    vec.pop();
                break;
            }
        }
        return vec.empty();
    }
};

 

posted @ 2016-03-07 13:58  zhangbaochong  阅读(151)  评论(0编辑  收藏  举报