最简单的方法,创建一个栈,遍历string s,对于每个char 如果是左括号则进入stack ,右括号则判断栈中最上面元素是否为对应的左括号即可!代码如下
> class Solution { public:
> bool isValid(string s) {
> stack<char>store;
> for(int x:s){
> if(x=='(' || x=='{' || x=='[') store.push(x);
> else {
> if(store.empty() || x==')' && store.top()!='(' || x==']' && store.top()!='[' || x=='}' && store.top()!='{')
> return false;
> else
> store.pop();
> }
> }
> return store.empty();
> } };