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.