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.
bool isValid(string s) {
//此题很明显使用栈
stack<char> st;
int len = s.size();
for (int i = 0; i < len; ++i)
{
if (s[i] == '(' || s[i] == '[' || s[i] == '{')
{
st.push(s[i]);
continue;
}
char c;
switch(s[i])
{
case '}': c = '{';break;
case ']': c = '['; break;
case ')': c = '('; break;
}
if (!st.empty() && c == st.top())
st.pop();
else
return false;
}
return st.empty();
}
本文介绍如何使用栈来解决括号有效性问题,详细解释了算法实现过程及正确闭合顺序的重要性。
911

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



