diff --git a/problems/0150.逆波兰表达式求值.md b/problems/0150.逆波兰表达式求值.md index fd3d69aa..47da06f6 100644 --- a/problems/0150.逆波兰表达式求值.md +++ b/problems/0150.逆波兰表达式求值.md @@ -325,6 +325,33 @@ func evalRPN(_ tokens: [String]) -> Int { return stack.last! } ``` - +Scala: +```scala +object Solution { + import scala.collection.mutable + def evalRPN(tokens: Array[String]): Int = { + val stack = mutable.Stack[Int]() // 定义栈 + // 抽取运算操作,需要传递x,y,和一个函数 + def operator(x: Int, y: Int, f: (Int, Int) => Int): Int = f(x, y) + for (token <- tokens) { + // 模式匹配,匹配不同的操作符做什么样的运算 + token match { + // 最后一个参数 _+_,代表x+y,遵循Scala的函数至简原则,以下运算同理 + case "+" => stack.push(operator(stack.pop(), stack.pop(), _ + _)) + case "-" => stack.push(operator(stack.pop(), stack.pop(), -_ + _)) + case "*" => stack.push(operator(stack.pop(), stack.pop(), _ * _)) + case "/" => { + var pop1 = stack.pop() + var pop2 = stack.pop() + stack.push(operator(pop2, pop1, _ / _)) + } + case _ => stack.push(token.toInt) // 不是运算符就入栈 + } + } + // 最后返回栈顶,不需要加return关键字 + stack.pop() + } +} +``` -----------------------