【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) {
        if(s.size() == 0)
            return true;
            
        stack<char> pareStack;
        pareStack.push(s[0]);
        
        for(string::size_type i = 1; i != s.size(); i++)
        {
            char temp;
            
            switch(s[i])
            {
                case ')' :
                    if(pareStack.size() != 0 && pareStack.top() == '(')
                        pareStack.pop();
                    else
                        return false;
                    break;
                
                case ']' :
                    if(pareStack.size() != 0 && pareStack.top() == '[')
                        pareStack.pop();
                    else
                        return false;
                    break;
                
                case '}' :
                    if(pareStack.size() != 0 && pareStack.top() == '{')
                        pareStack.pop();
                    else
                        return false;
                    break;
                default:
                    pareStack.push(s[i]);
            }
        }
        
        if(pareStack.size() == 0)
            return true;
            
        return false;
    }
};


你可能感兴趣的:(【Leetcode】Valid Parentheses)