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.