LeetCode - Valid Parentheses

来源:互联网 发布:linux系统品牌 编辑:程序博客网 时间:2024/05/17 06:16

题目描述:

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<string>#include<stack>using namespace std;class Solution {public:    bool isValid(string s) {stack<char> x;        for(int i=0;i<s.size();i++)        {        if(x.empty()) x.push(s[i]);                else if(s[i]=='{')        x.push(s[i]);        else if(s[i]=='[')        x.push(s[i]);        else if(s[i]=='(')        x.push(s[i]);                else if(s[i]=='}'&&x.top()=='{')        x.pop();        else if(s[i]=='}'&&x.top()!='{')        return false;        else if(s[i]==']'&&x.top()=='[')        x.pop();        else if(s[i]==']'&&x.top()!='[')        return false;        else if(s[i]==')'&&x.top()=='(')        x.pop();        else if(s[i]==')'&&x.top()!='(')        return false;        }        if(x.empty()) return true;        else return false;    }};


0 0
原创粉丝点击