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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (s.size() == 0) return true;
        stack<char> sck;
        sck.push(s[0]);
        for(int i = 1; i < s.size(); i++){
            switch (s[i]){
                case '(':
                case '{':
                case '[':
                sck.push(s[i]);
                break;
                case ')':
                if (sck.size() && sck.top() == '('){
                    sck.pop();
                }else{
                    return false;
                }
                break;
                case '}':
                if (sck.size() && sck.top() == '{'){
                    sck.pop();
                }else{
                    return false;
                }
                break;
                case ']':
                if (sck.size() && sck.top() == '['){
                    sck.pop();
                }else{
                    return false;
                }
                break;
            }
        }
        if (sck.empty()) return true;
        return false;
    }
};

 

posted @ 2013-07-14 17:51  一只会思考的猪  阅读(187)  评论(0编辑  收藏  举报