Valid Parentheses

来源:互联网 发布:ubuntu修改文件所有者 编辑:程序博客网 时间:2024/05/22 06:22

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 len = s.length();        if (len & 1)        {            return false;        }        if (len < 1)        {            return true;        }            stack<char> buf;        buf.push(s[0]);        for (int i = 1; i < len; i++)        {            char top = ' ';            if (!buf.empty())            {                top = buf.top();            }            if (s[i] == ')')            {                if (top == '(')                {                    buf.pop();                }                else                {                    return false;                }            }            else if (s[i] == ']')            {                if (top == '[')                {                    buf.pop();                }                else                {                    return false;                }            }            else if (s[i] == '}')            {                if (top == '{')                {                    buf.pop();                }                else                {                    return false;                }            }            else            {                buf.push(s[i]);            }        }        if (!buf.empty())        {            return false;        }        return true;    }};


0 0