题目链接: 力扣

题目描述: 逆波兰表达式把运算符写在后面,所以也叫后缀表达式。一般使用栈来进行求解。遇到数字就将数字压栈,遇到操作符,就将栈顶的两个元素取出计算,将计算结果再压入栈。

impl Solution { pub fn eval_rpn(tokens: Vec<String>) -> i32 { let mut stack: Vec<String> = Vec::new(); for token in tokens.into_iter() { let token = token.as_str(); if !(token == " " || token == "-" || token == "*" || token == "/") { stack.push(token.to_string()); } else { let x = stack.pop().unwrap().parse::<i32>().unwrap(); let y = stack.pop().unwrap().parse::<i32>().unwrap(); match token { " " => { stack.push((y x).to_string()); } "-" => { stack.push((y - x).to_string()); } "*" => { stack.push((y * x).to_string()); } "/" => { stack.push((y / x).to_string()); } _ => {} }; } } stack.pop().unwrap().parse::<i32>().unwrap() } }

leetcode高频100题(逆波兰表达式求值)(1)

运行结果

,