题解 |栈| #逆波兰表达式求值#

逆波兰表达式求值_牛客题霸_牛客网

逆波兰表达式(Reverse Polish Notation, RPN),也称为后缀表达式,是一种没有括号、运算符位于操作数之后的数学表达式表示法。逆波兰表达式的主要优点是它不需要使用括号来指示运算顺序,可以直接通过一个栈来解析和计算。

一、使用栈实现逆波兰表达式计算

#include <stack>
#include <string>
#include <iostream>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param tokens string字符串vector 
     * @return int整型
     */
     
    int evalRPN(vector<string>& tokens) {
     using namespace std;
        // write code here
        int l=0;
        int r=0;
        stack<int> stac;
        for (string str:tokens) {
            if ((str!="+" )&& (str!="-") && (str!="*") && (str!="/")) {
                stac.push(stoi(str) );
            }else {
                int r = stac.top();
                stac.pop();
                int l = stac.top();
                stac.pop();
                if (str=="+") {
                  stac.push(l+r);
                }else if(str=="-"){
                    stac.push(l-r);
                }else if(str=="*"){
                    stac.push(l*r);
                }else if(str=="/"){
                    stac.push(l/r);
                }
            }
        }
        return stac.top();

    }
};

二、扩展-中缀表达式转化成逆波兰表达式

中缀表达式(如 3 + 4 * 5)到逆波兰表达式(如 3 4 5 * +)的转换通常需要两个栈:一个用于存放操作数,另一个用于存放运算符。下面是具体的步骤:

  1. 初始化两个栈:一个用于操作数(这里不需要),另一个用于运算符。
  2. 从左到右扫描中缀表达式
  3. 遇到数字时,直接输出。
  4. 遇到运算符时,比较栈顶运算符的优先级与当前运算符的优先级:
    • 如果当前运算符的优先级高于栈顶运算符,则将当前运算符压入栈中。
    • 否则,弹出栈顶运算符并输出,重复此过程直到当前运算符的优先级高于栈顶运算符,然后将当前运算符压入栈中。
  5. 遇到左括号时,直接压入栈中。
  6. 遇到右括号时,弹出栈顶运算符并输出,直到遇到对应的左括号为止,然后将这对括号丢弃。
  7. 表达式结束后,依次弹出栈中的所有运算符并输出。
    #include <iostream>
    #include <stack>
    #include <vector>
    #include <unordered_map>
    
    using namespace std;
    
    vector<string> infixToPostfix(const vector<string>& tokens) {
        stack<string> operators;
        vector<string> output;
        unordered_map<string, int> precedence = {{"+", 1}, {"-", 1}, {"*", 2}, {"/", 2}};
    
        for (const auto& token : tokens) {
            if (isdigit(token[0])) {
                output.push_back(token);
            } else if (token == "(") {
                operators.push(token);
            } else if (token == ")") {
                while (!operators.empty() && operators.top() != "(") {
                    output.push_back(operators.top());
                    operators.pop();
                }
                operators.pop(); // Pop the '('
            } else if (precedence.count(token)) {  // Check if it's an operator
                while (!operators.empty() && precedence[token] <= precedence[operators.top()]) {
                    output.push_back(operators.top());
                    operators.pop();
                }
                operators.push(token);
            }
        }
    
        while (!operators.empty()) {
            output.push_back(operators.top());
            operators.pop();
        }
    
        return output;
    }
    
    int main() {
        vector<string> tokens = {"(", "3", "+", "4", ")", "*", "5"};
        vector<string> postfix = infixToPostfix(tokens);
    
        cout << "Postfix expression: ";
        for (const auto& token : postfix) {
            cout << token << " ";
        }
        cout << endl;
    
        return 0;
    }

  • 18
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
算法思路: 1. 创建两个:一个操作数和一个操作符。 2. 从左到右遍历表达式,遇到操作数就压入操作数,遇到操作符就与操作符中的顶元素比较优先级。 3. 如果当前操作符的优先级大于操作符顶的操作符优先级,就将当前操作符压入操作符。 4. 如果当前操作符的优先级小于或等于操作符顶的操作符优先级,就从操作数中弹出两个操作数,从操作符中弹出一个操作符,进行计算并将结果压入操作数,重复步骤3,直到当前操作符的优先级大于操作符顶的操作符优先级。 5. 当遍历完表达式后,如果操作符中还有操作符,就将操作数中剩余的操作数和操作符中的操作符按照步骤4计算,直到操作符为空。 6. 操作数中最后剩下的元素就是表达式的值。 算法实现: ```python def calculate(s: str) -> int: # 定义操作符优先级 priority = {'+': 1, '-': 1, '*': 2, '/': 2} # 定义操作数和操作符 nums = [] ops = [] i = 0 while i < len(s): # 跳过空格 if s[i] == ' ': i += 1 continue # 如果是数字,压入操作数 if s[i].isdigit(): j = i while j < len(s) and s[j].isdigit(): j += 1 nums.append(int(s[i:j])) i = j # 如果是操作符,比较优先级 else: while ops and priority[ops[-1]] >= priority[s[i]]: b = nums.pop() a = nums.pop() op = ops.pop() if op == '+': nums.append(a + b) elif op == '-': nums.append(a - b) elif op == '*': nums.append(a * b) elif op == '/': nums.append(int(a / b)) ops.append(s[i]) i += 1 # 处理剩余的操作符 while ops: b = nums.pop() a = nums.pop() op = ops.pop() if op == '+': nums.append(a + b) elif op == '-': nums.append(a - b) elif op == '*': nums.append(a * b) elif op == '/': nums.append(int(a / b)) # 返回操作数中最后剩下的元素 return nums[-1] ``` 算法分析: 1. 时间复杂度:遍历一遍表达式,时间复杂度为O(n);操作符和操作数中每个元素都只进出一次,所以总时间复杂度为O(n)。 2. 空间复杂度:操作符和操作数的最大长度为表达式的长度,所以空间复杂度为O(n)。 参考链接: 1. [LeetCode官方题解](https://leetcode-cn.com/problems/basic-calculator-ii/solution/jian-dan-zhan-jie-fa-by-jerry_nju/) 2. [算法珠玑(第2版)](https://book.douban.com/subject/33437322/)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值