标签:
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最优。
我的代码:
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; } };
标签:
原文地址:http://www.cnblogs.com/Scorpio989/p/4451713.html