题解 | #括号序列#
括号序列
http://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
用一个栈维护。
class Solution {
public:
bool isValid(string s) {
stack<int> stk;
int len = s.size();
for(int i = 0; i < len; i++)
{
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
stk.push(s[i]);
else
{
if(s[i] == ')')
if(stk.empty() || stk.top() != '(') return false;
else stk.pop();
if(s[i] == ']')
if(stk.empty() || stk.top() != '[') return false;
else stk.pop();
if(s[i] == '}')
if(stk.empty() || stk.top() != '{') return false;
else stk.pop();
}
}
if(!stk.empty()) return false;
return true;
}
};
查看20道真题和解析