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;

    }

};

 

你可能感兴趣的:(LeetCode)