20. 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.

在学习数据结构与算法的时候,我们就知道利用栈可以判定算术表达式是否合法。显而易见,本题必须使用stack作为辅助数据结构。

本题的解题思路比较简单,遍历表达式,凡是遇到({[则将符号压入栈中,遇到)}]则对栈执行pop操作,判读弹出的符号和遍历的符号是否配对。

class Solution {
public:
    bool isValid(string s) {
        int size = s.size();
        if (size == 0 || size % 2 != 0)
            return false;
        
        stack<char> container;    
        for (char ch : s) {
            switch (ch) {
                case '(':
                case '{':
                case '[':
                    container.push(ch);
                    break;
                
                case ')':
                case '}':
                case ']':
                    if (container.empty())
                        return false;
                    char top = container.top();
                    container.pop();
                    
                    if (ch == ')' && top != '(')
                        return false;
                    if (ch == '}' && top != '{')
                        return false;
                    if (ch == ']' && top != '[')
                        return false;
                    break;
            }
        }
        if (!container.empty())
            return false;
        return true;
    }
};

 

posted @ 2017-06-14 21:38  NaiveCoder  阅读(118)  评论(0)    收藏  举报