Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 224 · Expression Evaluation

Basic Calculator

LeetCode 224 · कठीण · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Stack saves (answer, sign) at each '('.

कठीणMathStringStackRecursion

मी 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. 1

    Digits → read the full number, add sign × number.

  2. 2

    '+' / '−' set the sign.

  3. 3

    '(' → push ans and sign, reset.

  4. 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 ans
स्टेप-थ्रू लोड होत आहे…

Basic 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.