Valid Parentheses

来源:互联网 发布:什么是科学精神知乎 编辑:程序博客网 时间:2024/06/05 14:09

题目:

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.


思想:

括号匹配,采用stack。


代码:

#include <iostream>#include <stack>#include <string>using namespace std;class Solution {public:    bool isValid(string s) {stack<char> mystack;for(int i=0;i<s.size();++i){switch(s[i]){case '(':mystack.push(s[i]);break;case '[':mystack.push(s[i]);break;case '{':mystack.push(s[i]);break;case ')':if(!mystack.empty()&&mystack.top()=='('){mystack.pop();}else{return false;}break;case ']':if(!mystack.empty()&&mystack.top()=='['){mystack.pop();}else{return false;}break;case '}':if(!mystack.empty()&&mystack.top()=='{'){mystack.pop();}else{return false;}default:break;}}        if(mystack.empty()) return true;else return false;    }};int main(){string str;cin>>str;Solution s;bool ret=s.isValid(str);if(ret)cout<<"YES!"<<endl;elsecout<<"NO!"<<endl;system("pause");return 0;}


0 0
原创粉丝点击