题意:

image.png

解题思路:

  1. 思路:(栈)
  2. 1. 遍历数组,依次入栈,遇到运算符,就弹出栈顶2个元素进行运算,最后将结果入栈;
  3. 注意:为了方便晕眩,第一个出栈元素放运算符右边
  4. ["4","13","5","/","+"]=> [4,13,5,/] => [4,2] => [4,2,+] => [6];

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param String[] $tokens
  4. * @return Integer
  5. */
  6. function evalRPN($tokens) {
  7. $stack = [];
  8. foreach ($tokens as $token) {
  9. switch ($token) {
  10. case '+':
  11. array_push($stack, array_pop($stack) + array_pop($stack));
  12. break;
  13. case '-':
  14. array_push($stack, -array_pop($stack) + array_pop($stack));
  15. break;
  16. case '*':
  17. array_push($stack, array_pop($stack) * array_pop($stack));
  18. break;
  19. case '/':
  20. $tmp = array_pop($stack);
  21. array_push($stack, intval(array_pop($stack) / $tmp));
  22. break;
  23. default:
  24. array_push($stack, (int)$token);
  25. }
  26. }
  27. return array_pop($stack);
  28. }
  29. }

GO代码实现:

  1. func evalRPN(tokens []string) int {
  2. stack := []int{}
  3. for _, val := range tokens {
  4. l := len(stack)
  5. switch val {
  6. case "+":
  7. stack = append(stack[:l-2], stack[l-2] + stack[l-1])
  8. case "-":
  9. stack = append(stack[:l-2], stack[l-2] - stack[l-1])
  10. case "*":
  11. stack = append(stack[:l-2], stack[l-2] * stack[l-1])
  12. case "/":
  13. stack = append(stack[:l-2], stack[l-2] / stack[l-1])
  14. default:
  15. num, _ := strconv.Atoi(val)
  16. stack = append(stack, num)
  17. }
  18. }
  19. return stack[0]
  20. }