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.
记得玩过一个手机游戏,叫做《黑客》,也有这个匹配括号的题。
class Solution {
public:
bool isValid(string s) {
if (s.length() % 2)
{
return false;
}
stack<char> brackets;
int i = 0;
while (i < s.length())
{
if (brackets.empty())
{
brackets.push(s[i]);
}
else
{
if ((brackets.top() == '(' && s[i] == ')') ||
brackets.top() == '[' && s[i] == ']' ||
brackets.top() == '{' && s[i] == '}' )
{
brackets.pop();
}
else
{
brackets.push(s[i]);
}
}
++i;
}
return brackets.size() == 0;
}
};
本文介绍了一个使用栈数据结构实现的有效括号匹配算法。该算法能够判断由'()', '[]', '{}
220

被折叠的 条评论
为什么被折叠?



