算法记录Day 11 | 栈与队列part02

61 阅读1分钟

算法记录Day 11 | 栈与队列part01

LeetCode 20-有效的括号

题目链接:leetcode.cn/problems/va…

题解
class Solution {
   public:
    stack<char> st;
    unordered_map<char, char> map;
    bool isValid(string s) {
        map[']'] = '[';
        map['}'] = '{';
        map[')'] = '(';
        for (int i = 0; i < s.size(); i++) {
            char c = s[i];
            auto iter = map.find(c);
            if (iter != map.end()) {
                if (st.empty()) {
                    return false;
                }
                char top = st.top();
                if (top == iter->second) {
                    st.pop();
                } else {
                    return false;
                }
            } else {
                st.push(c);
            }
        }
        return st.empty();
    }
};

LeetCode 1047-删除字符串中的所有相邻重复项

题目链接:leetcode.cn/problems/de…

题解
class Solution {
   public:
    string removeDuplicates(string s) {
        stack<char> st;
        for (int i = 0; i < s.size(); i++) {
            char c = s[i];
            if (!st.empty()) {
                char top = st.top();
                if (top == c) {
                    st.pop();
                } else {
                    st.push(c);
                }
            } else {
                st.push(c);
            }
        }
        string res = "";
        while (!st.empty()) {
            res += st.top();
            st.pop();
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

LeetCode 150-逆波兰表达式求值

题目链接:leetcode.cn/problems/ev…

题解
class Solution {
   public:
    int evalRPN(vector<string>& tokens) {
        stack<string> input;
        for (string e : tokens) {
            if (e != "+" && e != "-" && e != "*" && e != "/") {
                input.push(e);
            } else {
                long long nums1 = stoi(input.top());
                input.pop();
                long long nums2 = stoi(input.top());
                input.pop();
                long long temp;
                if (e == "+") {
                    temp = nums2 + nums1;
                } else if (e == "-") {
                    temp = nums2 - nums1;
                } else if (e == "*") {
                    temp = nums2 * nums1;
                } else {
                    temp = nums2 / nums1;
                }
                input.push(to_string(temp));
            }
        }

        return stoi(input.top());
    }
};