Valid Parentheses

来源:互联网 发布:无限网络 封优酷 编辑:程序博客网 时间:2024/05/29 08:03

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) {stack<char>stack;for (int i = 0; i < s.size(); ++i){if (s[i] == '(' || s[i] == '[' || s[i] == '{'){stack.push(s[i]);continue;}if (!stack.empty()){char c = stack.top();switch (s[i]){case ')':{if (c == '('){stack.pop();break;}elsereturn false;}case ']':{if (c == '['){stack.pop();break;}elsereturn false;}case '}':{if (c == '{'){stack.pop();break;}elsereturn false;}default:break;}}elsereturn false;}if (!stack.empty())return false;return true;}};


0 0