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.
栈实现括号匹配 (DFS)
//
// start: character matching
bool isValid (string const& s)
{
stack<char> chars;
string left = "([{";
string right = ")]}";
for(auto ch: s)
{
if(left.find(ch) != string::npos)// 如果是左半部分则入栈,如果是右半部分,取出栈顶部分进行匹配
chars.push(ch);
else
{
if(chars.empty() || chars.top() != left[right.find(ch)]) // 如果栈中没有元素或者栈顶元素不匹配则失败
return false; // find函数可以返回下标
else
chars.pop();
}
}
return chars.empty(); // 如果栈中还有元素则也匹配失败
}
// end
//