题意:
解题思路:
思路:(栈)
1. 遍历数组,依次入栈,遇到运算符,就弹出栈顶2个元素进行运算,最后将结果入栈;
注意:为了方便晕眩,第一个出栈元素放运算符右边
["4","13","5","/","+"]=> [4,13,5,/] => [4,2] => [4,2,+] => [6];
PHP代码实现:
class Solution {
/**
* @param String[] $tokens
* @return Integer
*/
function evalRPN($tokens) {
$stack = [];
foreach ($tokens as $token) {
switch ($token) {
case '+':
array_push($stack, array_pop($stack) + array_pop($stack));
break;
case '-':
array_push($stack, -array_pop($stack) + array_pop($stack));
break;
case '*':
array_push($stack, array_pop($stack) * array_pop($stack));
break;
case '/':
$tmp = array_pop($stack);
array_push($stack, intval(array_pop($stack) / $tmp));
break;
default:
array_push($stack, (int)$token);
}
}
return array_pop($stack);
}
}
GO代码实现:
func evalRPN(tokens []string) int {
stack := []int{}
for _, val := range tokens {
l := len(stack)
switch val {
case "+":
stack = append(stack[:l-2], stack[l-2] + stack[l-1])
case "-":
stack = append(stack[:l-2], stack[l-2] - stack[l-1])
case "*":
stack = append(stack[:l-2], stack[l-2] * stack[l-1])
case "/":
stack = append(stack[:l-2], stack[l-2] / stack[l-1])
default:
num, _ := strconv.Atoi(val)
stack = append(stack, num)
}
}
return stack[0]
}