[LeetCode] 20. Valid Parentheses

来源:互联网 发布:崔恺 知乎 编辑:程序博客网 时间:2024/06/06 23:17

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> stk;        for (auto c : s) {            if (c == '(' || c == '{' || c == '[')                stk.push(c);            else {                if (stk.empty() || (stk.top() != c - 1 && stk.top() != c - 2))                    return false;                stk.pop();            }        }        return stk.empty();    }};

这里写图片描述这里写图片描述