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.