11代码随想录训练营day11|栈和队列part02

1、LeetCode20

20. 有效的括号 - 力扣(LeetCode)

class Solution {
public:
    bool isValid(string s) {
        stack bracket;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
               bracket.push(s[i]);
            } else if (s[i] == ')' || s[i] == ']' || s[i] == '}') {
                if (bracket.size() == 0) return false;
                char temp = bracket.top();
                if (temp == '(' && s[i] != ')') return false;
                if (temp == '[' && s[i] != ']') return false;
                if (temp == '{' && s[i] != '}') return false;
                bracket.pop();
            }
        }
        if (bracket.size() != 0) return false;
        return true;
    }
};

2、LeetCode1047

1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)

class Solution {
public:
    string removeDuplicates(string s) {
        stack repeat;
        for (int i = 0; i < s.size(); i++) {
            if (repeat.size() == 0) {
                repeat.push(s[i]);
            } else {
                if (repeat.top() == s[i]) {
                    repeat.pop();
                } else {
                    repeat.push(s[i]);
                }
            }
        }
        int i = repeat.size() - 1;
        s.resize(i + 1);
        while (!repeat.empty()) {
            s[i--] = repeat.top();
            repeat.pop();
        }
        return s;
    }
};

3、LeetCode150

150. 逆波兰表达式求值 - 力扣(LeetCode)

class Solution {
public:
    int evalRPN(vector& tokens) {
        stack operate;
        for (int i = 0; i < tokens.size(); i++) {
            if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/") {
                operate.push(stoll(tokens[i]));
            } else {
                long long a = operate.top();
                operate.pop();
                long long b = operate.top();
                operate.pop();
                long long temp;
                if (tokens[i] == "+") temp = a + b;
                if (tokens[i] == "-") temp = b - a;
                if (tokens[i] == "*") temp = a * b;
                if (tokens[i] == "/") temp = b / a;
                operate.push(temp);
            }
        }
        return operate.top();
    }
};

你可能感兴趣的:(代码随想录训练营,数据结构,c++)