题目源自于Leetcode。
题目: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.
思路:由于这里的多种括号,所以不能用原来常用的一个int型来模拟栈的情况。因为这种情况下栈内的内容不只有'('这一种。需要借助完整的栈来做。
STL中的stack:
下面解法使用了STL中的stack容器。stack是一种适配器(adapter)类,默认的底层实现为顺序容器vector。
stack的声明方法:stack<int> st;
stack的基本操作有:
压入栈stack.push(i)。
弹出栈stack.pop()。 注意,pop()是没有返回值的。所以想取得栈顶的话,需要先top再pop。
返回栈的当前元素个数stack.size()。
返回当前栈顶元素stack.top()。 注意调用它之前最好先判断栈是否为空。
当前栈是否为空stack.empty()。
题目解答:
class Solution {
public:
bool isValid(string s) {
stack<int> st;
int n = s.length();
int i;
for(i=0;i<n;i++)
{
switch(s[i])
{
case '(': st.push(1); break;
case '[': st.push(2); break;
case '{': st.push(3); break;
case ')': if(st.empty() || st.top() != 1) return false; st.pop(); break;
case ']': if(st.empty() || st.top() != 2) return false; st.pop(); break;
case '}': if(st.empty() || st.top() != 3) return false; st.pop(); break;
}
}
if(st.size() == 0)
return true;
else
return false;
}
};