LeetCode | 20. Valid Parentheses

来源:互联网 发布:jquery weui.min.js 编辑:程序博客网 时间:2024/05/17 23:59

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.

其实是括号匹配问题,用栈来实现比较方便.

//3ms ACclass Solution {public:    bool isValid(string s) {        int len = s.length();        if(len%2 == 1)            return false;        stack<char> symbol;        for(int i=0;i<len;i++)        {            if(s[i]=='(' || s[i]=='{' || s[i]=='[')            {                symbol.push(s[i]);            }            else                        //右括号            {                if(symbol.empty())      //栈为空,肯定不匹配                {                    return false;                }                switch(s[i])                {                    case ')':{                        if(symbol.top() != '(')                            return false;                        break;                    }                    case ']':{                        if(symbol.top() != '[')                            return false;                        break;                    }                    case '}':{                        if(symbol.top() != '{')                            return false;                        break;                    }                    default:                        break;                }                symbol.pop();            }        }        if(symbol.empty())            return true;        else            return false;    }};
1 0
原创粉丝点击