Evaluate Reverse Polish Notation
LeetCode 150 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Operands on a stack; operator pops two.
నేను Evaluate Reverse Polish Notation (LeetCode 150) ను ఇలా పరిష్కరించాను — Expression Evaluation ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
In RPN every operator applies to the two most recent values, so push numbers on a stack and, at an operator, pop two, combine, and push the result.
Approach
- 1
Number → push.
- 2
Operator → b = pop, a = pop, push a op b.
- 3
Division truncates toward zero: int(a / b).
నేను ఎలా పరిష్కరించాను
Stack evaluationPythonO(n) time
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
#store the operation with operator as key in a map
operations = {
"*": lambda a,b:a*b,
"+": lambda a,b:a+b,
"-": lambda a,b:a-b,
"/": lambda a,b:int(a/b)
}
stack = []
for token in tokens:
if token in operations:
b = stack.pop()
a = stack.pop()
operation = operations[token]
cur_val = operation(a,b)
stack.append(cur_val)
else:
stack.append(int(token))
return stack.pop()Evaluate Reverse Polish Notation — తరచూ అడిగే ప్రశ్నలు
Evaluate Reverse Polish Notation వెనుక ఉన్న intuition ఏమిటి?
In RPN every operator applies to the two most recent values, so push numbers on a stack and, at an operator, pop two, combine, and push the result.
Evaluate Reverse Polish Notation (LeetCode 150) ను ఎలా పరిష్కరించాలి?
1. Number → push. 2. Operator → b = pop, a = pop, push a op b. 3. Division truncates toward zero: int(a / b).
Evaluate Reverse Polish Notation యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(n). (Accepted approach: Stack evaluation.)
Evaluate Reverse Polish Notation లో సాధారణ పొరపాట్లు ఏమిటి?
Pop order matters for − and /. Python's // floors negatives; int(a / b) truncates as required.