mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 0150.逆波兰表达式求值.md Scala版本
This commit is contained in:
@ -325,6 +325,33 @@ func evalRPN(_ tokens: [String]) -> Int {
|
|||||||
return stack.last!
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
-----------------------
|
-----------------------
|
||||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user