Basic Calculator
LeetCode 224 · కఠినం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Stack saves (answer, sign) at each '('.
నేను Basic Calculator (LeetCode 224) ను ఇలా పరిష్కరించాను — Expression Evaluation ప్యాటర్న్లోని ఒక కఠినం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Without * or /, an expression is just signed numbers added up. Keep a running answer and the current sign. On '(' save the answer and sign so far on a stack and start fresh; on ')' finish the inner value, apply the saved sign, and add the saved answer.
Approach
- 1
Digits → read the full number, add sign × number.
- 2
'+' / '−' set the sign.
- 3
'(' → push ans and sign, reset.
- 4
')' → ans = saved_ans + saved_sign × ans.
నేను ఎలా పరిష్కరించాను
Sign stackPythonO(n) time
class Solution:
def calculate(self, s: str) -> int:
#if it is a number
#calculate number and add to answer with the current sign
#if it's ( - add current answer and sign to the stack
#if it's ) - take last sign, last total and apply to the ans
#if it's - - sign =-1
#if it's + sign=1
i=0
ans = 0
sign = 1
stack = []
while i<len(s):
if s[i].isdigit():
num = 0
#"123"
while i<len(s) and s[i].isdigit():
num = num*10+int(s[i])
i+=1
ans+=num*sign
i-=1 #we incremented extra
elif s[i]=="+":
sign = 1
elif s[i]=="-":
sign =-1
elif s[i]=="(":
stack.append(ans)
stack.append(sign)
#reset
ans=0
sign = 1
elif s[i]==")":
last_sign = stack.pop()
last_total=stack.pop()
ans = ans*last_sign
ans+=last_total
i+=1
return ansBasic Calculator — తరచూ అడిగే ప్రశ్నలు
Basic Calculator వెనుక ఉన్న intuition ఏమిటి?
Without * or /, an expression is just signed numbers added up. Keep a running answer and the current sign. On '(' save the answer and sign so far on a stack and start fresh; on ')' finish the inner value, apply the saved sign, and add the saved answer.
Basic Calculator (LeetCode 224) ను ఎలా పరిష్కరించాలి?
1. Digits → read the full number, add sign × number. 2. '+' / '−' set the sign. 3. '(' → push ans and sign, reset. 4. ')' → ans = saved_ans + saved_sign × ans.
Basic Calculator యొక్క time, space complexity ఎంత?
Time: O(n). Space: O(n). (Accepted approach: Sign stack.)
Basic Calculator లో సాధారణ పొరపాట్లు ఏమిటి?
Step back one index after reading a multi-digit number.