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; } };