Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 1209 · Stack Simulation / String Processing

Remove All Adjacent Duplicates in String II

LeetCode 1209 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Stack of [char, count]; pop at count k.

मध्यमStringStack

मी Remove All Adjacent Duplicates in String II (LeetCode 1209) असा सोडवला — Stack Simulation / String Processing पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

Keep a stack of (character, run length). A matching character extends the top run; when a run reaches k it disappears, which may bring two runs of the same character together on the next push.

Approach

  1. 1

    New character → push with count 1.

  2. 2

    Same as top → increment; at k, pop.

  3. 3

    Rebuild from the stack.

मी कसा सोडवला

Run-length stackPythonO(n) time
class Solution:
    def removeDuplicates(self, s: str, k: int) -> str:
        stack =[]
        for char in s:
            if len(stack)==0 or stack[-1]["char"]!=char:
                stack.append({"char":char,"count":1})
            else:
                stack[-1]["count"]+=1
                if stack[-1]["count"]==k:
                    stack.pop()
        
        res =""
        for item in stack:
            res+=item["char"]*item["count"]
        return res

स्टेप-थ्रू लोड होत आहे…

Remove All Adjacent Duplicates in String II — वारंवार विचारले जाणारे प्रश्न

Remove All Adjacent Duplicates in String II मागील intuition काय आहे?

Keep a stack of (character, run length). A matching character extends the top run; when a run reaches k it disappears, which may bring two runs of the same character together on the next push.

Remove All Adjacent Duplicates in String II (LeetCode 1209) कसा सोडवावा?

1. New character → push with count 1. 2. Same as top → increment; at k, pop. 3. Rebuild from the stack.

Remove All Adjacent Duplicates in String II ची time आणि space complexity किती आहे?

Time: O(n). Space: O(n). (Accepted approach: Run-length stack.)

Remove All Adjacent Duplicates in String II मध्ये सामान्य चुका कोणत्या?

Rebuilding with += in a loop is fine here; ''.join is faster for big inputs.