Re: [閒聊] 每日leetcode

作者: dont   2024-11-21 01:38:33
2516. Take K of Each Character From Left and Right
## 思路
Sliding window
找最長的window使剩下的字元個數都>= K
result = 整個字串長度扣掉window長度
先掃整個字串記錄abc字元個數
檢查counter[ch] 如果<k就更新left
## Code
```python
class Solution:
def takeCharacters(self, s: str, k: int) -> int:
if k == 0:
return 0
counter = Counter(s)
if not all(counter[ch] >= k for ch in 'abc'):
return -1
res = left = 0
for right, ch in enumerate(s):
counter[ch] -= 1
while counter[ch] < k:
counter[s[left]] += 1
left += 1
res = max(res, right - left + 1)
return len(s) - res
```

Links booklink

Contact Us: admin [ a t ] ucptt.com