day 11 第五章 栈与队列 20. 有效的括号 1047. 删除字符串中的所有相邻重复项 150. 逆波兰表达式求值

刷题笔记

//20 自己写的ac了,但是写的不好,可以参考卡哥的。点这里

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

            }
        }
        if(st.empty())  return true;
        else return false;
    }
};

//1047
//自己ac了 , 跟卡哥差不多

class Solution {
public:
    string removeDuplicates(string s) {
        stack<char> st;
        string result;
        for(int i = 0; i < s.size(); i++){
            if(st.empty()) st.push(s[i]);
            else{
                if(st.top() == s[i]){
                    st.pop();
                }
                else st.push(s[i]);
            }
        }
        while(!st.empty()){
            result += st.top(); //给字符串添加字符
            st.pop();
        }
        reverse(result.begin(),result.end()); //reverse是原地反转,无返回值,参数是指针
        return result;
    }
};

//150
//挺简单的,但是要注意很多细节!!!
//longlong不能改成int,会溢出,因为给的不一定是个int的数

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<long long> st; //栈里存的long long类型
        for(int i = 0; i < tokens.size(); i++){
            if(tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/"){ 
                st.push(stoll(tokens[i]));//stoll函数!!!
            }
            else{
                long long a = st.top();
                st.pop();
                long long b = st.top();
                st.pop();
                if(tokens[i] == "+") st.push(b + a);//“”双引号不能写成单引号。和python不一样
                else if(tokens[i] == "-") st.push(b - a);//注意是b-a
                else if(tokens[i] == "*") st.push(b * a);
                else st.push(b / a);
            }
 
        }
        return st.top();
    }
};

重点

stoll函数:此函数将在函数调用中作为参数提供的字符串转换为long long int。它解析str并将其内容解释为指定基数的整数,并将其作为long long int类型的值返回。
(s to longlong这么记)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值