20. 有效的括号

  1. 题目链接

  2. 解题思路:括号匹配问题,优先想到栈。

  3. 代码

    class Solution {
    public:
        bool isValid(string s) {
            stack<char> st;
            for (auto &ch : s) {
                // 如果是右括号,那么必须得有一个相匹配的左括号
                if (ch == ')') {
                    if (st.empty() || st.top() != '(') {
                        return false;
                    }
                    st.pop();
                } else if(ch == '}') {
                    if (st.empty() || st.top() != '{') {
                        return false;
                    }
                    st.pop();
                } else if (ch == ']') {
                    if (st.empty() || st.top() != '[') {
                        return false;
                    }
                    st.pop();
                } else { // 如果是左括号,那么直接压入栈
                    st.push(ch);
                }
            }
            // 别忘记,栈要空,否则就是左括号太多了
            return st.empty();
        }
    };
    
posted @ 2024-12-18 10:51  ouyangxx  阅读(13)  评论(0)    收藏  举报