导航

LeetCode 20. Valid Parentheses

Posted on 2016-09-18 17:18  CSU蛋李  阅读(112)  评论(0编辑  收藏  举报

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.

 

因为例如"([{}])"也是正确的,明显我们要用到栈,如果匹配(即对应的是左右括号)则出栈,否则入栈,最后栈为空为真,否则为假

但是要注意“]["也为假,但是LeetCode的测试用例并没有考虑到这种情况,因为我第一次提交的时候也没有考虑到这种情况但是提交

却通过了

 

class Solution {
public:
    bool isValid(string s) {
        if (0 == s.size())return true;
        map<char, int> map;
        map['('] = 0;map['['] = 1;map['{'] = 2;map[')'] = 3;map[']'] = 4;map['}'] = 5;
        stack<char> sta;
        for (size_t i = 0;i < s.size();++i)
        {
            if (sta.size()&&(map[s[i]] != map[sta.top()] && map[s[i]] % 3 == map[sta.top()] % 3)&&map[sta.top()]<map[s[i]])
            {
                sta.pop();
            }
            else
                sta.push(s[i]);
        }
        if (sta.size())return false;
        else return true;
    }
};