Leetcode 227. Basic Calculator II

本文介绍了一种使用栈数据结构实现的基本计算器解决方案,能够处理简单的数学表达式,包括加、减、乘、除运算,并讨论了如何优化代码以提高效率。

Problem

mplement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

Note: Do not use the eval built-in library function.

Credits:
Special thanks to @ts for adding this problem and creating all test cases。

我的想法就是用两个stack, 一个记数字,一个记操作符,

写出来的代码好丑。。

class Solution {
    bool isOpt( const char& ch) {
        if(ch == '+' || ch == '-' || ch == '*' || ch == '/') return true;
        return false;
    }
    void calc( stack<int>& num_stk, stack<char>& opt_stk){
        int num2 = num_stk.top(); num_stk.pop();
        int num1 = num_stk.top(); num_stk.pop();
        char opt = opt_stk.top(); opt_stk.pop();
 
        int rst = 0;
        switch( opt) {
            case '+' :
                rst = num1 + num2;
                break;
            case '-' :
                rst = num1 - num2;
                break;            
            case '*' :
                rst = num1 * num2;
                break;
            case '/' :
                rst = num1 / num2;
                break;
        }
        num_stk.push(rst);
    }
    
public:
    int calculate(string s) {
        const int N = s.size();
        stack<int> num_stk;
        stack<char> opt_stk;
        
        unordered_map<char,int> preced;
        preced['+'] = 0; preced['-'] = 0; preced['*'] = 1; preced['/'] = 1;
        
        for( int i = 0; i < N; i++) {
            if( s[i] == ' ') continue;
            
            if(isdigit(s[i])){
                int num = 0;
                while( i < N && !isOpt(s[i])) {
                    if(s[i] == ' ') { i++;continue;}
                    num = num*10 + s[i] -'0';
                    i++;
                }
                i--;
                num_stk.push(num);
            }
            else {
                if(opt_stk.empty() || preced[s[i]] > preced[opt_stk.top()]){
                    opt_stk.push(s[i]);
                }
                else{
                    calc(num_stk, opt_stk);
                    i--;
                }
            }
        }
        
        while( !opt_stk.empty() ){
            calc(num_stk, opt_stk);
        }
        return num_stk.top();
    }
};

优化版

这个想法比较巧妙 : 第一步就只是去处乘号和除号,第二步就计算加减号

class Solution {

public:
    int calculate(string s) {
        char preSign = '+';
        int pre_num = 0;
        stack<int> num_stk;
        
        const int N = s.size();
        for( int i = 0; i < N; i++){
            if(isdigit(s[i])) {
                pre_num = pre_num*10 + s[i] - '0';
            }
            if( ( !isdigit(s[i]) && s[i] != ' ')|| i == N -1 ) {
                int top = 0;
                switch (preSign) {
                    case '+' : 
                        num_stk.push(pre_num);
                        break;
                    case '-' :
                        num_stk.push(-pre_num);
                        break;
                    case '*' : {
                        top = num_stk.top(); num_stk.pop();
                        num_stk.push(top * pre_num);
                        break;}
                    case '/' :{
                        top = num_stk.top(); num_stk.pop();
                        num_stk.push(top/pre_num);
                        break;}                     
                }
                preSign = s[i];
                pre_num = 0;
            }
        }
        
        int rst = 0;
        while(!num_stk.empty()){
            int top = num_stk.top();
            num_stk.pop();
            rst += top;
        }
        return rst;
    }
};


问题升级:
如果表达式中还有 ( 和 ) ,怎么办 
写出来有问题,回头再看吧。。。 写的有点烦躁。。。。
stack<int> num_stk;
stack<char> opt_stk;

void do_calc(){
    int num1 = num_stk.top(); num_stk.pop();
    int num2 = num_stk.top(); num_stk.pop();
    
    char opt = opt_stk.top(); opt_stk.pop();
    int rst = 0;
    switch(opt){
        case '+' :
            rst = num2 + num1;
            break;
        case '-':
            rst = num2 - num1;
            break;
        case '*' :
            rst = num2 * num1;
            break;
        case '/':
            rst = num2 / num1;
            break;
    }
    num_stk.push(rst);
}

int calc( const string& str) {

    
    unordered_map<char,int> preced;
    preced['*'] = 1; preced['/'] = 1;preced['+'] = 0;preced['-'] = 0;preced['('] = -1;
    
    const int N = str.size();
    
    for( int i = 0; i < N; i++){
        // for numbers
        if(str[i] == ' ') continue;
        if(isdigit(str[i])){
            int num = 0;
            for( ; i < N ; i++ ) {
                if(str[i] == ' ') continue;
                if(!isdigit(str[i])) break;
                num = num*10 + str[i] - '0';
            }
            num_stk.push(num);
        }
        // for operators
        if(opt_stk.empty() || str[i] == '(' || preced[str[i]] > preced[opt_stk.top()]) {
            opt_stk.push(str[i]);
        }
        else if( preced[str[i]] <= preced[opt_stk.top()]) {
           do_calc();
           
        }
        else if(str[i] == ')') {
            while(opt_stk.top() != '(') {
                do_calc();
            }
            opt_stk.pop();
        }
    }
    
    while(!opt_stk.empty()){
        do_calc();
    }
    return num_stk.top();
}



【四轴飞行器】非线性三自由度四轴飞行器模拟器研究(Matlab代码实现)内容概要:本文围绕非线性三自由度四轴飞行器模拟器的研究展开,重点介绍了基于Matlab的建模与仿真方法。通过对四轴飞行器的动力学特性进行分析,构建了非线性状态空间模型,并实现了姿态与位置的动态模拟。研究涵盖了飞行器运动方程的建立、控制系统设计及数值仿真验证等环节,突出非线性系统的精确建模与仿真优势,有助于深入理解飞行器在复杂工况下的行为特征。此外,文中还提到了多种配套技术如PID控制、状态估计与路径规划等,展示了Matlab在航空航天仿真中的综合应用能力。; 适合人群:具备一定自动控制理论基础和Matlab编程能力的高校学生、科研人员及从事无人机系统开发的工程技术人员,尤其适合研究生及以上层次的研究者。; 使用场景及目标:①用于四轴飞行器控制系统的设计与验证,支持算法快速原型开发;②作为教学工具帮助理解非线性动力学系统建模与仿真过程;③支撑科研项目中对飞行器姿态控制、轨迹跟踪等问题的深入研究; 阅读建议:建议读者结合文中提供的Matlab代码进行实践操作,重点关注动力学建模与控制模块的实现细节,同时可延伸学习文档中提及的PID控制、状态估计等相关技术内容,以全面提升系统仿真与分析能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值