首页 > 试题广场 >

逆波兰表达式求值

[编程题]逆波兰表达式求值
  • 热度指数:34611 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个逆波兰表达式,求表达式的值。

数据范围:表达式长度满足 ,表达式中仅包含数字和 + ,- , * , / ,其中数字的大小满足
示例1

输入

["2","1","+","4","*"]

输出

12
示例2

输入

["2","0","+"]

输出

2
用例输入:["5","4","/","1","*"]
预期输出:1
实际输出:1.25

叼!
发表于 2023-01-19 21:51:18 回复(1)
用计算逆波兰表达式的流程就行,遇到数字就压栈,遇到运算符就弹出栈顶两个数进行计算,然后把计算结果压入栈中,直到栈中只剩下最后一个数,就是整个逆波兰表达式的计算结果。
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param tokens string字符串一维数组 
     * @return int整型
     */
    public int evalRPN (String[] tokens) {
        // write code here
        Stack<Integer> stack = new Stack<>();
        for(int i = 0; i < tokens.length; i++) {
            if(isDigit(tokens[i])){
                stack.push(Integer.parseInt(tokens[i]));
            }else{
                if(tokens[i].equals("+")){
                    int num2 = stack.pop();
                    int num1 = stack.pop();
                    stack.push(num1 + num2);
                }else if(tokens[i].equals("-")){
                    int num2 = stack.pop();
                    int num1 = stack.pop();
                    stack.push(num1 - num2);
                }else if(tokens[i].equals("*")){
                    int num2 = stack.pop();
                    int num1 = stack.pop();
                    stack.push(num1 * num2);
                }else if(tokens[i].equals("/")){
                    int num2 = stack.pop();
                    int num1 = stack.pop();
                    stack.push(num1 / num2);
                }
            }
        }
        return stack.pop();
    }
    
    private boolean isDigit(String s) {
        try{
            Integer.parseInt(s);
            return true;
        }catch(Exception e) {
            return false;
        }
    }
}

发表于 2021-12-22 20:14:20 回复(1)
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param tokens string字符串vector 
     * @return int整型
     */
    int evalRPN(vector<string>& tokens) {
        // write code here
        // 时间复杂度O(N),空间复杂度O(N)
        stack<string> stk;
        int n1, n2, res;
        for (string &s : tokens) {
            if (s == "+" || s == "-" || s == "*" || s == "/") {
                n2 = stoi(stk.top());
                stk.pop();
                n1 = stoi(stk.top());
                stk.pop();
                if (s == "+") res = n1 + n2;
                else if (s == "-") res = n1 - n2;
                else if (s == "*") res = n1 * n2;
                else res = n1 / n2;
                stk.push(to_string(res));
            } else stk.push(s);
        }
        return stoi(stk.top());
    }
};

发表于 2022-04-06 00:39:30 回复(0)
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param tokens string字符串一维数组 
# @return int整型
#
class Solution:
    def evalRPN(self , tokens: List[str]) -> int:
        # write code here
        """
            逆波兰表达式
                1. 维护一个栈,栈中只保存数值 -> stack = []
                2. 如果遇到数,存到栈中
                3. 如果遇到运算符,从stack中取出两个元素进行相应的计算并存储回栈中
        """

        stack = []

        for elem in tokens:
            # 如果是运算符
            if elem in "+-*/":
                # 从栈中取出两个元素
                first = stack.pop()
                second = stack.pop()

                # 根据运算符进行对应计算
                if elem == "+":
                    stack.append(second + first)
                elif elem == "-":
                    stack.append(second - first)
                elif elem == "*":
                    stack.append(second * first)
                else:
                    stack.append(int(second / first))
                
            # 如果数
            else:
                stack.append(int(elem))

        # 最后取出栈的元素
        return stack.pop()

发表于 2022-10-26 21:45:01 回复(0)
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param tokens string字符串vector 
     * @return int整型
     */
    int evalRPN(vector<string>& tokens) {
        // write code here
        stack<int> sta;
        for(int i=0;i<tokens.size();i++)
        {
            if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/")
            {
            int num=sta.top();sta.pop();int num1=sta.top();sta.pop();
                
            if(tokens[i]=="+"){sta.push(num+num1);}
            if(tokens[i]=="-"){sta.push(num1-num);}
            if(tokens[i]=="*"){sta.push(num*num1);}
            if(tokens[i]=="/"){sta.push(num1/num);}
            }
            else {sta.push(stoi(tokens[i]));}
        }
        return sta.top();
        
    }
};

发表于 2022-07-16 21:56:54 回复(1)
class Solution:
    def evalRPN(self , tokens: List[str]) -> int:
        # write code here
        ls = []
        for i in range(len(tokens)):
            if tokens[i] in ["+","-","*","/"]:
                l1 = ls.pop()
                l2 = ls.pop()
                res = str(int(eval(l2 + tokens[i] + l1)))
                ls.append(res)
            else:
                ls.append(tokens[i])
        return int(ls[-1])

发表于 2022-01-18 22:10:36 回复(1)
逆波兰就是后缀表达式,遇到符号就pop两个栈顶元素计算,别忘了把计算结果再压入栈!

import java.util.*;

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param tokens string字符串一维数组
     * @return int整型
     */
    public int evalRPN (String[] tokens) {
        Stack<Integer> stack = new Stack<>();

        for (String token : tokens) {
            if (token.equals("+")) {
                int b = stack.pop();
                int a = stack.pop();
                stack.push(a + b);
            } else if (token.equals("-")) {
                int b = stack.pop();
                int a = stack.pop();
                stack.push(a - b);
            } else if (token.equals("*")) {
                int b = stack.pop();
                int a = stack.pop();
                stack.push(a * b);
            } else if (token.equals("/")) {
                int b = stack.pop();
                int a = stack.pop();
                stack.push(a / b);
            } else {
                stack.push(Integer.parseInt(token));
            }
        }

        return stack.pop();
    }
}


发表于 2024-05-30 22:47:02 回复(0)
如图,所示,逆波兰表达式是这样的,数字在前,运算符在后,遇到运算符就向前找两个数进行该运算符的运算,运算结果仍然保留在该位置,开始往后找下一个运算符,进行同样的操作。
这个过程我们可以用栈来模拟,是数字就入栈,遇到运算符,就从栈里面出两个数据进行运算,再把运算结果放到栈里面,最后栈里面剩下的元素,就是最终结果
难点:
1.理解逆波兰表达式的含义,如何用栈来模拟
2.把字符串转化为数字(可以用专门的函数来实现)
代码如下:
#include<iostream>
#include<string>
#include<vector>
#include<stack>
using namespace std;


int NumberTransform(string& str) {
    int size = str.size();
    if (str[0] == '-') { //负数
        if (size - 1 == 3) { //三位数
            return -((str[1] - '0') * 100 + ((str[2] - '0') * 10) + (str[3] - '0'));
        } else if (size - 1 == 2) { //两位数
            return -((str[1] - '0') * 10 + (str[2] - '0'));
        } else { //一位数
            return -(str[1] - '0');
        }

    } else { //正数
        if (size == 3) { //三位数
            return (str[0] - '0') * 100 + (str[1] - '0') * 10 + (str[2] - '0');
        } else if (size == 2) { //两位数
            return (str[0] - '0') * 10 + (str[1] - '0');
        } else { //一位数
            return str[0] - '0';
        }
    }
}
int Calculation(stack<int>& st, string& str) {//计算
    int a = 0;
    int b = 0;
    a = st.top();
    st.pop();
    b = st.top();
    st.pop();
    if (str == "+")
        return b + a;
    else if (str == "-")
        return b - a;
    else if (str == "*")
        return b * a;
    else
        return b / a;
}
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param tokens string字符串vector
     * @return int整型
     */
    int evalRPN(vector<string>& tokens) {
        // write code here
        int size = tokens.size(); //字符串的个数
        //辅助栈
        stack<int> st;//存为数字的字符对应的10进制数

        string  str;//临时接收字符串
        int i = 0; //访问vector的下标
        for (i = 0; i < size; i++) {//容器的遍历,这里最好使用迭代器
        //但这样的遍历也是可以的
            str = tokens[i];
            if (str == "+" || str == "-" || str == "*" || str == "/") { //取数计算
                int result = Calculation(st, str);
                st.push(result);
            } else { //把字符串转换为数字入栈
                int temp = NumberTransform(str);
                //这个函数仅仅能针对这个题,
                //其实这个字符串转化为数的功能是有专门额函数的
                //整数 stoi(字符串)  比如 stoi("123") 它的返回值就是 123
                // stoi("-123")  它的返回值就是 -123 这是简单的应用
                st.push(temp);
            }
        }
        return st.top();
    }
};


发表于 2023-01-19 12:36:17 回复(0)
只说一点 注意出栈的顺序a,b -> b operator a  !
public int evalRPN (String[] tokens) {
    ArrayDeque<Integer> stack = new ArrayDeque<>();
    for (String t : tokens) {
        if (t.equals("+") || t.equals("-") 
            || t.equals("*") || t.equals("/")) {
            int a = stack.pop(), b = stack.pop();
            if (t.equals("+")) stack.push(b+a);
            else if (t.equals("-")) stack.push(b-a);
            else if (t.equals("*")) stack.push(b*a);
            else stack.push(b/a);
        } else {
            stack.push(Integer.parseInt(t));
        }
    }
    return stack.peek();
}
发表于 2022-01-11 12:42:48 回复(0)
import java.util.*;

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param tokens string字符串一维数组
     * @return int整型
     */
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();

        for (String token : tokens) {
            if (token.equals("+") || token.equals("-") || token.equals("*") ||
                    token.equals("/")) {
                int a = stack.pop();
                int b = stack.pop();
                switch (token) {
                    case "+":
                        stack.push(b + a);
                        break;
                    case "-":
                        stack.push(b - a);
                        break;
                    case "*":
                        stack.push(b * a);
                        break;
                    case "/":
                        stack.push(b / a);
                        break;
                }
            } else {
                stack.push(Integer.parseInt(token));
            }
        }

        return stack.pop();
    }
}
发表于 2025-05-13 16:28:58 回复(0)
using System;
using System.Collections.Generic;


class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param tokens string字符串一维数组
     * @return int整型
     */
    public int evalRPN (List<string> tokens) {

        //一个字符,直接输出
        if (tokens.Count == 1)
            return int.Parse(tokens[0]);

        //三个字符,直接算
        if (tokens.Count == 3)
            return operiation(int.Parse(tokens[0]), int.Parse(tokens[1]), tokens[2]);

        Stack<string> stack = new Stack<string>();
        int number;
        foreach (var token in tokens) {
            if (!int.TryParse(token, out number)) {
                int y = int.Parse(stack.Pop());
                int x = int.Parse(stack.Pop());
                int result = operiation(x, y, token);
                stack.Push(result.ToString());
            } else
                stack.Push(token);
        }

        return int.Parse(stack.Pop());

    }

    public int operiation(int x, int y, string oper) {

        switch (oper) {
            case "+" :
                x = x + y;
                break;
            case "-" :
                x =  x - y ;
                break;
            case "*" :
                x = x * y;
                break;
            case "/" :
                x = x / y ;
                break;
            default:
                break;
        }

        return x;
    }
}

发表于 2025-04-15 23:57:33 回复(0)
#include<cctype>
class Solution {
    unordered_map<string,function<int(int,int)>>map;
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param tokens string字符串vector
     * @return int整型
     */
     Solution(){
        map["+"]=[](int a,int b){return a+b;};
        map["-"]=[](int a,int b){return a-b;};
        map["*"]=[](int a,int b){return a*b;};
        map["/"]=[](int a,int b){return a/b;};
     }
    int evalRPN(vector<string>& tokens) {
        stack<int>p;
        for(string tmp:tokens){
            if(map.count(tmp))
            {
               int b=p.top();
               p.pop();
               int a=p.top();
               p.pop();
               p.push(map[tmp](a,b));
            }
            else{
                p.push(stoi(tmp));
            }
        }
        return p.top();
    }
};
发表于 2025-04-08 19:05:05 回复(0)
package main

import (

    "strconv"
    "strings"

)

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param tokens string字符串一维数组
 * @return int整型
 */
func evalRPN( tokens []string ) int {
    // write code here
    chr :=[]int{}
    comp := "+ - * /"
    if len(tokens) == 1{
        num ,_ :=strconv.Atoi(tokens[0])  
        return num
    }
    for i:=0; i< len(tokens);i++{
        if strings.Contains(comp, tokens[i]){
            switch tokens[i]{
                case "+":
                    num := chr[len(chr)-2] + chr[len(chr)-1]
                    chr = chr[:len(chr)-2]
                    chr = append(chr, num)
                case "-":
                    num := chr[len(chr)-2] - chr[len(chr)-1]
                    chr = chr[:len(chr)-2]
                    chr = append(chr, num)
                case "*":
                    num := chr[len(chr)-2] * chr[len(chr)-1]
                    chr = chr[:len(chr)-2]
                    chr = append(chr, num)
                case "/":
                    num := chr[len(chr)-2] / chr[len(chr)-1]
                    chr = chr[:len(chr)-2]
                    chr = append(chr, num)
            }
           
        }
        i2, err := strconv.Atoi(tokens[i])
        if err == nil{
            chr = append(chr, i2)
        }
       
    }
    return chr[0]
   
}
发表于 2025-04-06 22:45:17 回复(0)
import java.util.*;
import java.util.Stack;

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param tokens string字符串一维数组
     * @return int整型
     */
    public int evalRPN (String[] tokens) {
        // write code here
        int result = 0;
        int num1 = 0;
        int num2 = 0;
        Stack<Integer> stack = new Stack<Integer>();
        for(String s: tokens){
            if(s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")){
                if(!stack.isEmpty())num1 = stack.pop();
                if(!stack.isEmpty())num2 = stack.pop();
                switch(s){
                    case "+": result = num2 + num1; break;
                    case "-": result = num2 - num1; break;
                    case "*": result = num2 * num1; break;
                    case "/": result = num2 / num1; break;
                }
                stack.push(result);    
            }else{
                int num = Integer.parseInt(s);
                stack.push(num);
            }
        }
        return stack.pop();
    }
}
发表于 2025-03-17 17:00:30 回复(0)
#include <iostream>
#include <vector>
#include <stack>
#include <string>
using namespace std;
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param tokens string字符串vector
     * @return int整型
     */
    //匹配问题,使用栈进行模拟
    stack <int> nums;//运算数字栈
    bool nonum(string c) {
        if (c == "+" || c == "-" || c == "*" || c == "/") {
            return true;
        } else {
            return false;
        }
    }
    int compute(int a, int b, string c) {
        if (c == "+") {
            return a + b;
        } else if (c == "-") {
            return a - b;
        } else if (c == "*") {
            return a * b;
        } else {
            if (b == 0) {
                return -1;
            }
            return a / b;
        }
    }
    // 手动实现字符串转整数功能
    int my_stoi(const string& str) {
        int result = 0;
        int sign = 1;
        size_t i = 0;
        if (str[0] == '-') {
            sign = -1;
            i = 1;
        }
        for (; i < str.length(); ++i) {
            result = result * 10 + (str[i] - '0');
        }
        return result * sign;
    }

    int evalRPN(vector<string>& tokens) {
        int temp1, temp2;
        string c;
        for (int i = 0; i < tokens.size(); i++) {
            c = tokens[i];
            if (!nonum(c)) { //如果是数字,入栈
                nums.push(my_stoi(c));
            } else {
                if (nums.size() < 2) {
                    return -1;
                } else {
                    temp2 = nums.top();
                    nums.pop();
                    temp1 = nums.top();
                    nums.pop();
                    nums.push(compute(temp1, temp2, c));
                }
            }
        }
        return nums.top();
        // write code here
    }
};
能在C++98运行的算法
发表于 2025-03-06 15:01:03 回复(0)
import java.util.*;

/**
 * NC216 逆波兰表达式求值
 * @author d3y1
 */
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param tokens string字符串一维数组 
     * @return int整型
     */
    public int evalRPN (String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        int leftVal,rightVal;
        for(String token: tokens){
            switch(token){
                case "+": rightVal=stack.pop();leftVal=stack.pop();stack.push(leftVal+rightVal); break;
                case "-": rightVal=stack.pop();leftVal=stack.pop();stack.push(leftVal-rightVal); break;
                case "*": rightVal=stack.pop();leftVal=stack.pop();stack.push(leftVal*rightVal); break;
                case "/": rightVal=stack.pop();leftVal=stack.pop();stack.push(leftVal/rightVal); break;
                default: stack.push(Integer.parseInt(token)); break;
            }
        }

        // + - * /
        // String regex = "[+\\-*/]";
        // for(String token: tokens){
        //     if(token.matches(regex)){
        //         rightVal = stack.pop();
        //         leftVal = stack.pop();
        //         switch(token){
        //             case "+": stack.push(leftVal+rightVal); break;
        //             case "-": stack.push(leftVal-rightVal); break;
        //             case "*": stack.push(leftVal*rightVal); break;
        //             case "/": stack.push(leftVal/rightVal); break;
        //             default: break;
        //         }
        //     }else{
        //         stack.push(Integer.parseInt(token));
        //     }
        // }

        return stack.pop();
    }
}

发表于 2025-02-02 12:24:23 回复(0)
for (String s : tokens) {
    if (s.matches("[\\+\\-\\*\\/]")) { // 匹配 +-*/ Java双反斜杠\\表示一个\转义
    }
}

发表于 2025-01-31 17:12:00 回复(0)
题目描述的也太不清楚了,除法要取整,最后的结果也要取整,鬼知道
发表于 2025-01-09 16:48:59 回复(0)
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param tokens string字符串一维数组 
 * @param tokensLen int tokens数组长度
 * @return int整型
 */
#include <stdio.h>
int evalRPN(char** tokens, int tokensLen ) {
    // write code here
    int n[10000]={0},top=-1,i,j,k,l,a,b,m=0;
    
    
    
    
    for(i=0;i<tokensLen;i++){
        
        if(**(tokens+i)=='+'){
            b=n[top--];
            a=n[top--];
            n[++top]=(a+b);
            continue;
        }
        if((**(tokens+i)=='-')&&*(*(tokens+i)+1)=='\0'){
            b=n[top--];
            a=n[top--];
            n[++top]=(a-b);
            continue;
        }
        if(**(tokens+i)=='*'){
            b=n[top--];
            a=n[top--];
            n[++top]=(a*b);
            continue;
        }
        if(**(tokens+i)=='/'){
            b=n[top--];
            a=n[top--];
            n[++top]=(a/b);
            continue;
        }
        if(**(tokens+i)>='0'&&**(tokens+i)<='9'){
              //k=sizeof(*(tokens+i))/;
              m=0,j=0;
              while(*(*(tokens+i)+j)!='\0') {
                    m=m*10+(*(*(tokens+i)+j)-'0');
                    j++;
              }
              n[++top]=m;
              continue;
        }
        if(**(tokens+i)=='-'&&*(*(tokens+i)+1)!='\0'){
              //k=sizeof(*(tokens+i))/;
              m=0,j=1;
              while(*(*(tokens+i)+j)!='\0') {
                    m=m*10+(*(*(tokens+i)+j)-'0');
                    j++;
              }
              n[++top]=0-m;
              continue;
        }



        printf("%c",**(tokens+i));
    }
    return n[top];
    
}

发表于 2024-11-16 09:03:27 回复(0)
static int compute(String[] tokens) {
        int[] params = new int[2];

        for (int i = 0; i < tokens.length; i++) {
            switch (tokens[i]) {
                case "+":
                    params[0] = params[0] + params[1];
                    break;
                case "-":
                    params[0] = params[0] - params[1];
                    break;
                case "*":
                    params[0] = params[0] * params[1];
                    break;
                case "/":
                    params[0] = params[0] / params[1];
                    break;
                default:
                    //计算数据存放的index位置
                    params[i & 1] = Integer.parseInt(tokens[i]);
                    break;
            }
        }
        return params[0];
    }

发表于 2024-10-23 21:15:43 回复(1)

问题信息

难度:
64条回答 7100浏览

热门推荐

通过挑战的用户

查看代码
逆波兰表达式求值