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