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


你可能感兴趣的:(String,function,input)