跳转至

有效的括号⚓︎

Leetcode链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
public:
    bool isValid(string s) {
        if (s.size() % 2) return false;

        stack<char> stk;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '(') stk.push(')');
            else if (s[i] == '[') stk.push(']');
            else if (s[i] == '{') stk.push('}');
            else if (stk.empty() || stk.top() != s[i]) return false;
            else stk.pop();
        }

        return stk.empty();
    }
};