[leetcode]Valid Parentheses题解

来源:互联网 发布:java jdk 编辑:程序博客网 时间:2024/05/17 08:27
描述
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> k;for (string::size_type index =0;index!=s.size();++index){if (s[index]=='('||s[index]=='{'||s[index]=='['){k.push(s[index]);}else{switch(s[index]){case ')':if (!k.empty()&&k.top()=='('){k.pop();} else return false; break;case '}':if (!k.empty()&&k.top()=='{') { k.pop(); } else return false; break;case ']':if (!k.empty()&&k.top()=='[') { k.pop(); } else return false; break;}}}return k.empty();}


0 0
原创粉丝点击