可以评估这个后缀表达式吗?
6 2 3 + - 3 8 2 / + * 2 5 3 +
答案 0 :(得分:7)
是的,它可以。
S = new empty stack
while not eof
t = read token
if t is a binary operator
y = pop(S)
x = pop(S)
push(S, t(x, y))
else
push(S, t)
print the contents of the stack S
答案 1 :(得分:3)
简单地遍历整个数组并且:
push
您遇到的每个number
operation token
- pop
两个数字并评估操作push
您的操作返回堆栈的结果就是这样。对于空间,复杂度为linear, O(n)
,对于空间,复杂度为linear, O(n)
,因为我们使用堆栈来存储数字。
整个代码使用堆栈(JavaScript
):
/*
Function to perform operation with two numbers.
@param {String} Operation type.
@param {Number} Number 1.
@param {Number} Number 2.
@returns {Number} Result of performing the operation.
*/
var performOperation = function performOperation(operation, num1, num2) {
switch (operation) {
case '+': return num1 + num2;
case '-': return num1 - num2;
case '*': return ~~(num1 * num2);
case '/': return ~~(num1 / num2);
default: console.error('Unknown operation: ', operation);
}
};
/*
Function to check if variable holds an operation type.
@param {Any} Token.
@returns {Boolean} If token is string with operation type.
*/
var isOperation = function isNumber(token) {
// map of supported operations
var map = {
'+': true,
'-': true,
'*': true,
'/': true
}
return !!map[token];
};
var evaluatePolishNotation = function evaluatePolishNotation(tokens) {
var stack = [];
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (isOperation(token)) {
var number1 = stack.pop();
var number2 = stack.pop();
stack.push( performOperation(token, number2, number1) );
} else {
stack.push( parseInt(tokens[i], 10) );
}
}
return stack.pop();
}
但您可以通过使用常量空间O(1)来改善它!了解有关算法here的更多信息。