20. Valid Parentheses

来源:互联网 发布:数字电视机顶盒软件 编辑:程序博客网 时间:2024/05/15 08:24

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:    stack<char> left;    queue<char> right;    bool isValid(string s) {        if(s.size()==1) return false;        for(int i=0;i<s.size();i++)        {            if(s[i]=='('||s[i]=='{'||s[i]=='[')                left.push(s[i]);            else if(s[i]==')'||s[i]=='}'||s[i]==']')                {                    if(left.empty()) return false;                    char ch=left.top();                    switch(s[i])                    {                        case ')': if(ch!='(') return false;break;                        case ']': if(ch!='[') return false;break;                        case '}': if(ch!='{') return false;break;                    }                    if(!left.empty())                        left.pop();                }        }        if(!left.empty()) return false;        return true;    }};

思路:其实就是简单的堆栈,假如是左括号就压栈,右括号就弹出来判断

0 0
原创粉丝点击