Remove All Adjacent Duplicates in String II
LeetCode 1209 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Stack of [char, count]; pop at count k.
నేను 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
New character → push with count 1.
- 2
Same as top → increment; at k, pop.
- 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.