Valid Parentheses

来源:互联网 发布:淘宝开店保证金好退吗 编辑:程序博客网 时间:2024/04/29 11:15

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.

#include<iostream>#include<vector>#include<string>#include<stack>using namespace std;bool isValid(string s) {if (s.empty())return true;stack<char>CharStack;for (int i = 0; i != s.size();++i){if (s[i] == '(' || s[i] == '{' || s[i] == '[')CharStack.push(s[i]);else{if (CharStack.empty())return false;switch (s[i]){case ')':if (CharStack.top() == '(')CharStack.pop();elsereturn false;break;case ']':if (CharStack.top() == '[')CharStack.pop();elsereturn false;break;case'}':if (CharStack.top() == '{')CharStack.pop();elsereturn false;break;default:break;}}}return CharStack.empty();}


 

0 0
原创粉丝点击