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最优。时间:2ms

我的代码:

class Solution {
public:
    bool isValid(string s) {
        stack<char> sign;
        for (string::const_iterator iter = s.begin(); iter != s.end(); ++iter){
            switch (*iter){
                case '(':
                case '{':
                case '[':sign.push(*iter); break;
                case ')':
                    if (sign.size()&&sign.top() == '('){
                        sign.pop(); break;
                    }
                case '}':
                    if (sign.size() && sign.top() == '{'){
                        sign.pop(); break;
                    }
                case ']':
                    if (sign.size() && sign.top() == '['){
                        sign.pop(); break;
                    }
                    return false;
                default:break;
            }
        }
        if (sign.size())
            return false;
        else
            return true;
    }
};

 

posted on 2015-04-23 20:43  NealCaffrey989  阅读(130)  评论(0编辑  收藏  举报