Leetcode_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
        stack<char> myStack;
        for(int i = 0; i< s.length(); i++)
        {
            switch(s[i]){
                case '{': 
                case '[':
                case '(':  myStack.push(s[i]); break;
                case ')':{
                        if(myStack.empty() ||myStack.top() != '(' )
                           return false;
                         myStack.pop();
                         break;
                }
                case ']': {
                        if(myStack.empty() ||myStack.top() != '[' )
                           return false;
                         myStack.pop();
                         break;
                }
                case '}': {
                        if(myStack.empty() ||myStack.top() != '{' )
                           return false;
                         myStack.pop();
                         break;
                }
                default : return false;
            }
        }
        if(myStack.empty())
            return true;
        else
             return false;
    }
};

 

posted @ 2013-06-05 09:55  冰点猎手  阅读(129)  评论(0编辑  收藏  举报