20. Valid Parentheses

来源:互联网 发布:火星时代网络课程 编辑:程序博客网 时间:2024/05/15 05:07

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) {        stack<char> ss;        int len = s.size();        for(int i = 0; i < len; ++ i)        {            if(ss.empty())                ss.push(s[i]);            else            {                if(s[i] == ')')                {                    if(ss.top() != '(') return false;                    else ss.pop();                }                else if(s[i] == '}')                {                    if(ss.top() != '{') return false;                    else ss.pop();                }                else if(s[i] == ']')                {                    if(ss.top() != '[') return false;                    else ss.pop();                }                else                    ss.push(s[i]);            }        }        if(!ss.empty()) return false;        return true;    }};
0 0
原创粉丝点击