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

发布时间 2023-09-18 11:24:37作者: zz子木zz

20.有效的括号

卡哥demo

class Solution {
public:
    bool isValid(string s) {
        
        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('}');
            //else if(st.top() != s[i] || st.empty()) return false;	//报错,会有空栈top()的风险
            else if(st.empty() || st.top() != s[i]) return false;
            else st.pop();
        }
        if(st.empty())  return true;
        else    return false;
    }
};

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

mydemo--(自己思路)--failed

我的代码只能进行判断是否能全部消除完毕

class Solution {
public:
    bool removeDuplicates(string s) {
        if(s.size() %2 != 0)     return false;
        stack<char> st;
        for(int i =0; i < s.size(); i++){
            if(stack.empty())   stack.push(s[i]);
            else if(stack.top == s[i])  stack.pop();
            else    stack.push(s[i])
        }
        if(stack.empty())   return true;
        else return false;
    }
};

卡哥demo1

栈,然后最后转换成string

class Solution {
public:
    string removeDuplicates(string s) {
        stack<char> st;
        for(char ch:s){
            if(st.empty() || ch != st.top())   st.push(ch);
            else st.pop();
        }
        string result = "";
        while(!st.empty()){   //只要栈不为空
            result += st.top();
            st.pop();
        }
        reverse(result.begin(), result.end());
        return result;
    }
};

卡哥demo2

用字符串模拟栈

class Solution {
public:
    string removeDuplicates(string s) {
        string result;
        for(char ch : s){
            if(result.empty() || result.back() != ch){ //注意顺序,否则有操作空字符串的风险
                result.push_back(ch);
            }
            else{
                result.pop_back();
            }
        }
        return result;
    }
};

150.逆波兰表达式求值

卡哥代码

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<long long> st;    //leetcode给的数据很大,需要用longlong类型
        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);//运算顺序别反了,是num2在前
                if(tokens[i] == "-") st.push(num2 - num1);//运算顺序别反了,是num2在前
                if(tokens[i] == "*") st.push(num2 * num1);//运算顺序别反了,是num2在前
                if(tokens[i] == "/") st.push(num2 / num1);//运算顺序别反了,是num2在前
            }
            else{
                st.push(stoll(tokens[i]));
            }
        }

        int result = st.top();
        st.pop();    //释放内存是好习惯
        return result;
    }
};