150. 逆波兰表达式求值

根据逆波兰表示法,求表达式的值。
有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
说明:
整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

image.png

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. func evalRPN(tokens []string) int {
  7. stack :=make([]int,0)
  8. for i:=0;i<len(tokens);i++{
  9. if tokens[i]=="+" {
  10. f :=stack[len(stack)-1]
  11. s:= stack[len(stack)-2]
  12. stack =stack[:len(stack)-2]
  13. stack = append(stack,f+s)
  14. }else if tokens[i]=="-" {
  15. f :=stack[len(stack)-1]
  16. s:= stack[len(stack)-2]
  17. stack =stack[:len(stack)-2]
  18. stack = append(stack,s-f)
  19. }else if tokens[i]=="*" {
  20. f :=stack[len(stack)-1]
  21. s:= stack[len(stack)-2]
  22. stack =stack[:len(stack)-2]
  23. stack = append(stack,s*f)
  24. }else if tokens[i]=="/" {
  25. f :=stack[len(stack)-1]
  26. s:= stack[len(stack)-2]
  27. stack =stack[:len(stack)-2]
  28. stack = append(stack,s/f)
  29. }else {
  30. s,_:= strconv.Atoi(tokens[i])
  31. stack = append(stack,s)
  32. }
  33. }
  34. return stack[0]
  35. }
  36. func main() {
  37. fmt.Println(evalRPN([]string{"2", "1", "+", "3", "*"}))
  38. fmt.Println(evalRPN([]string{"4", "13", "5", "/", "+"}))
  39. fmt.Println(evalRPN([]string{"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"}))
  40. }

image.png

精简版代码

func evalRPN(tokens []string) int {
    number := []int{}
    for _, val := range tokens{
        l := len(number)
        switch val {
        case "+":
            number  = append(number[:l -2], number[l-2] + number[l-1])
        case "-":
            number  = append(number[:l -2], number[l-2] - number[l-1])
        case "*":
            number  = append(number[:l -2], number[l-2] * number[l-1])
        case "/":
            number  = append(number[:l -2], number[l-2] / number[l-1])
        default:
            num, _ := strconv.Atoi(val)
            number  = append(number, num)
        }
    }
    return number[0]
}