力扣练习之逆波兰表达式求值

我爱海鲸 2023-05-29 21:23:28 暂无标签

简介中级算法、其他、Rust

原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-medium/xw20mv/

解法一(python)

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for token in tokens:
            if token.isdigit() or (token.startswith("-") and token[1:].isdigit()):
                stack.append(int(token))
            else:
                b, a = stack.pop(), stack.pop()
                if token == "+":
                    stack.append(a + b)
                elif token == "-":
                    stack.append(a - b)
                elif token == "*":
                    stack.append(a * b)
                else:
                    stack.append(int(a / b))
        return stack[0]

解法二(Rust)

impl Solution {
    pub fn eval_rpn(tokens: Vec<String>) -> i32 {
    let mut stack = Vec::new();
        for token in tokens {
            if let Ok(num) = token.parse::<i32>() {
                stack.push(num);
            } else {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                match token.as_str() {
                    "+" => stack.push(a + b),
                    "-" => stack.push(a - b),
                    "*" => stack.push(a * b),
                    "/" => stack.push(a / b),
                    _ => (),
                }
            }
        }
        stack.pop().unwrap()
    }
}

思路:

解法一

我们使用 isdigit() 方法来判断 token 是否为数字,同时为了处理负数,可以使用 startsWith() 方法来判断一个 ‘-’ 符号出现在 token 字符串的开头。如果遇到运算符,我们弹出栈顶的两个元素,根据运算符进行运算,并将结果压入栈中。最终,栈中仅剩下一个元素,即为表达式的计算结果。

解法二

我们可以使用栈来进行求解。具体的,我们从左到右遍历 tokens,对于每个 token,如果它是一个数字,则将其转换为整数并压入栈中,如果它是一个运算符,则弹出栈顶的两个元素,进行运算,并将结果压入栈中。最后剩下的唯一一个元素即为计算结果。

你好:我的2025