代码随想录Day11

57 阅读1分钟

20. 有效的括号

力扣题目链接

文章讲解

栈的拿手好戏!| LeetCode:20. 有效的括号 20.有效括号.gif

#include <iostream>
#include <stack>
using namespace std;

class Solution {
public:
    bool isValid(string s) {
        // 如果字符串的长度为奇数,直接false
        if ((s.size() % 2) != 0) {
            return false;
        }
        stack<char> st;
        for (int i = 0; i < s.size(); ++i) {
            if (s[i] == '(') {
                st.push(')');
            }
            else if (s[i] == '{') {
                st.push('}');
            }
            else if (s[i] == '[') {
                st.push(']');
            }
            // 第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号 return false
            // 第二种情况:遍历字符串匹配的过程中,发现栈里没有我们要匹配的字符。所以return false
            else if (st.empty() || st.top() != s[i]) {
                return false;   
            }
            else {
                st.pop();
            }

        }
        // 第一种情况:此时我们已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false,否则就return true
        return st.empty();
    }
};

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

力扣题目链接

文章讲解

栈的好戏还要继续!| LeetCode:1047. 删除字符串中的所有相邻重复项

1047.删除字符串中的所有相邻重复项.gif

string removeDuplicates(string s) {
        stack<char> st;
        for(char snum : s) {
            if (st.empty() || snum != st.top()) {
                st.push(snum);
            }
            // 字符相等则出栈
            else {
                st.pop();
            }
        }
        string result = "";
        while (!st.empty()) {
            result += st.top();
            st.pop();
        }
        reverse(result.begin(), result.end());
        return result;
    }

150. 逆波兰表达式求值

力扣题目链接

文章讲解

栈的最后表演! | LeetCode:150. 逆波兰表达式求值

150.逆波兰表达式求值.gif

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<long long> st;
        for (int i = 0; i < tokens.size(); ++i) {
            if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
                long long num1 = st.top();
                st.pop();
                long long num2 = st.top();
                st.pop();
                if (tokens[i] == "+") {
                    st.push(num2 + num1);
                }
                if (tokens[i] == "-") {
                    st.push(num2 - num1);
                }
                if (tokens[i] == "*") {
                    st.push(num2 * num1);
                }
                if (tokens[i] == "/") {
                    st.push(num2 / num1);
                }
            } else {
                // stoll函数将字符串转换成长整型
                st.push(stoll(tokens[i]));
            }
        }
        int result = st.top();
        st.pop();
        return result;
    }