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.
括号匹配的问题,使用栈解决。(注意,访问栈元素时要先判断栈是否为空)
C++实现代码如下:
#include#include #include using namespace std;class Solution {public: bool isValid(string s) { size_t index=0; stack ss; while(index
运行结果:
#include#include #include using namespace std;class Solution{public: bool isValid(string s) { stack st; int i; for(i=0;i<(int)s.size();i++) { switch(s[i]) { case '(': case '[': case '{': st.push(s[i]); break; case ')': if(st.empty()||st.top()!='(') return false; st.pop(); break; case ']': if(st.empty()||st.top()!='[') return false; st.pop(); break; case '}': if(st.empty()||st.top()!='{') return false; st.pop(); break; } } if(st.empty()) return true; else return false; }};int main(){ Solution s; string str="((()))"; cout< <