NC52.有效括号序列

有效括号序列

https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2?tpId=196&rp=1&ru=%2Fexam%2Foj&qru=%2Fexam%2Foj&sourceUrl=%2Fexam%2Foj%3Ftab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D196&difficulty=&judgeStatus=&tags=&title=&gioEnter=menu

NC52.有效括号序列

class Solution {
public:
    /**
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    bool isValid(const string& s) {
        // write code here
        const std::unordered_map<char, char> brackets {
            {')', '('}, {'}', '{'}, {']', '['}
        };
        std::stack<char> st;
        for (auto& i : s) {
            auto itor = brackets.find(i);
            if (itor != brackets.end() && !st.empty() && st.top() == itor->second) {
                st.pop();
                continue;
            }
            st.push(i);
        }
        return st.empty();
    }
};

解题思路:

难点1:栈的最基础应用之一,括号匹配,能看出用栈基本就成了一半;

难点2:unordered_map的使用会精简代码;

知识点:

知识点1:C++中stack详解

#include <stack>

//empty()			堆栈为空则返回真
//pop()			移除栈顶元素
//push()			在栈顶增加元素
//size()			返回栈中元素数目
//top()			返回栈顶元素

std::stack<char> st;
st.top();
st.pop();
st.push(i);
st.empty();
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务