Valid Parentheses

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;
    }
};


你可能感兴趣的:(Valid Parentheses)