力扣 20. 有效的括号

71 阅读1分钟

🔗 leetcode.cn/problems/va…

题目

  • 给一个字符串由'('')''{''}''['']' 组成
  • 判断字符串是否有效,有效的前提是括号成对出现
  • 左括号按照顺序闭合,右括号能找到成对的左括号

思路

  • stack 模拟

代码

class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        unordered_map<char, char> m;
        m[')'] = '(';
        m['}'] = '{';
        m[']'] = '[';
        for (char ch : s) {
            if (m.count(ch) == 0) {
                st.push(ch);
                continue;
            }
            if (st.empty() || st.top() != m[ch]) return false;
            st.pop();            
        }

        if (st.empty()) return true;
        return false;
    }
};