题解 | #有效括号序列#

有效括号序列

https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2

#include <unordered_map>
class Solution {
public:
    /**
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    bool isValid(string s) {
        stack<int> st;
        unordered_map<char, char> hash = {{'[', ']'}, {'{', '}'}, {'(', ')'}};
        for (auto &c: s) {
            if (hash.count(c)) {
                st.push(hash[c]);
            } else {
                if (st.empty() || st.top() != c) {
                    return false;
                }
                st.pop();
            }
        }
        return st.empty();
    }
};

思路:栈模拟。

* 遇到左括号,将对应的右括号压入栈。

* 遇到右括号,如果栈顶没有匹配,则返回false,否则将栈顶弹出。

最后还需要判断栈为空。

全部评论

相关推荐

04-25 10:45
东南大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务