首页 > 编程语言 >代码随想录算法训练营第十一天 20.有效的括号 | 1047. 删除字符串中的所有相邻重复项 | 150. 逆波兰表达式求值

代码随想录算法训练营第十一天 20.有效的括号 | 1047. 删除字符串中的所有相邻重复项 | 150. 逆波兰表达式求值

时间:2023-01-26 00:55:40浏览次数:52  
标签:第十一天 string 括号 随想录 st push result 求值 else

栈应用 lc20 有效的括号

本题考验的是对栈操作的理解,关键在于梳理逻辑,写出判断条件。在写代码之前想清楚可能存在的不匹配的情况(左括号多了,右括号不匹配最近的左括号,右括号多了)

class Solution {
public:
    bool isValid(string s) {
        stack<char> expect;
        for (char c : s){
            //出现左括号的情况
            if(c=='(') expect.push(')');
            else if(c=='[') expect.push(']');
            else if(c=='{') expect.push('}');
            //出现右括号的情况
            //栈已经为空,或没有与最近的左括号匹配 返回false
            else if(expect.empty() || expect.top() != c) return false;
            //右括号匹配,弹出
            else expect.pop();
        }
        //检查栈是否为空,有可能有多余的左括号
        return expect.empty();
    }
};

栈应用 lc1047 删除字符串中的所有相邻重复项

本题可以使用栈来解决,在栈为空或者栈顶元素与字符串遍历元素不相同时进行压栈,相等时出栈。直接使用string来搭建栈的结构可以节省掉将栈转为string的工作。

使用string搭建栈

class Solution {
public:
    string removeDuplicates(string s) {
        string result;
        for(char c : s ){
            if(result.empty() || result.back() != c){
                result.push_back(c);
            }
            else{
                result.pop_back();
            }
        }
        return result;
    }
};

代码随想录 直接使用stack

class Solution {
public:
    string removeDuplicates(string S) {
        stack<char> st;
        for (char s : S) {
            if (st.empty() || s != st.top()) {
                st.push(s);
            } else {
                st.pop(); // s 与 st.top()相等的情况
            }
        }
        string result = "";
        while (!st.empty()) { // 将栈中元素放到result字符串汇总
            result += st.top();
            st.pop();
        }
        reverse (result.begin(), result.end()); // 此时字符串需要反转一下
        return result;

    }
};

栈应用 lc150 逆波兰表达式求值

本题重要概念在于逆波兰表达式,或后缀表达式。后缀表达式对计算机十分友好,让计算机立刻明白了计算的顺序。使用栈来进行对后缀表达式进行求值分为以下步骤:

  1. 建立空栈来存储数据
  2. 遍历输入的后缀表达式
  3. 遇到数字时将其压入栈
  4. 遇到符号时,弹出两个数字并使用该符号进行计算,将得到的值压入栈

后缀表达式 和 逆序遍历二叉树也有些关系。

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> st;
        for (string s : tokens){
            if (s == "+" || s == "-" || s == "*" || s == "/"){
                int n2 = st.top(); 
                st.pop();
                int n1 = st.top();
                st.pop();
                if(s == "+") st.push(n1 + n2);
                else if(s == "-") st.push(n1 - n2);
                else if(s == "*") st.push(n1 * n2);
                else if(s == "/") st.push(n1 / n2);
            }
            else{
                st.push(stol(s));
            }
        }
        return st.top();
    }
};

标签:第十一天,string,括号,随想录,st,push,result,求值,else
From: https://www.cnblogs.com/frozenwaxberry/p/17067502.html

相关文章