leetcode---valid-parentheses---栈

来源:互联网 发布:星海乐器知乎 编辑:程序博客网 时间:2024/05/17 23:34

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:    bool isValid(string s)     {        int n = s.size();        if(n == 0)            return true;        if(n & 1 == 1)            return false;        int cnt = 0;        stack<char> sk;        for(int i=0; i<n; i++)        {            if(s[i] == '(' || s[i] == '[' || s[i] == '{')            {                cnt++;                sk.push(s[i]);            }            else if(s[i] == ')' || s[i] == ']' || s[i] == '}')            {                cnt--;                if(cnt < 0)                    return false;                char c = sk.top();                sk.pop();                if(s[i] == ')')                {                    if(c != '(')                        return false;                }                else if(s[i] == ']')                {                    if(c != '[')                        return false;                }                else                {                    if(c != '{')                        return false;                }            }         }        return cnt == 0 ? true : false;    }};
原创粉丝点击