LeetCode 2516. 每种字符至少取 K 个

2516. 每种字符至少取 K 个

给你一个由字符 'a''b''c' 组成的字符串 s 和一个非负整数 k 。每分钟,你可以选择取走 s 最左侧 还是 最右侧 的那个字符。

你必须取走每种字符 至少 k 个,返回需要的 最少 分钟数;如果无法取到,则返回-1 。

示例 1:

输入:s = "aabaaaacaabc", k = 2
输出:8
解释:
从 s 的左侧取三个字符,现在共取到两个字符 'a' 、一个字符 'b' 。
从 s 的右侧取五个字符,现在共取到四个字符 'a' 、两个字符 'b' 和两个字符 'c' 。
共需要 3 + 5 = 8 分钟。
可以证明需要的最少分钟数是 8 。

示例 2:

输入:s = "a", k = 1
输出:-1
解释:无法取到一个字符 'b' 或者 'c',所以返回 -1 。

提示:

  • 1 <= s.length <= 10^5
  • s 仅由字母 'a''b''c' 组成
  • 0 <= k <= s.length

提示 1

Start by counting the frequency of each character and checking if it is possible.


提示 2

If you take x characters from the left side, what is the minimum number of characters you need to take from the right side? Find this for all values of x in the range 0 ≤ x ≤ s.length.


提示 3

Use a two-pointers approach to avoid computing the same information multiple times.

解法:滑动窗口

必须取走每种字符 至少 k 个,也就是必须取走字符 'a''b''c' 每种字符都要 至少 k 个。

class Solution {
    public int takeCharacters(String s, int k) {
        int n = s.length();
        if (n < 3 * k) {
            return -1;
        }
        // 记录滑动窗口的长度
        int ans = 0;
        // 记录滑动窗口外每种字符的个数
        int[] outWindow = new int[3];
        int left = 0;
        int right = 0;
        for (int i = 0; i < n; i++) {
            outWindow[s.charAt(i) - 'a']++;
        }
        if (outWindow[0] < k || outWindow[1] < k || outWindow[2] < k) {
            return -1;
        }
        while (right < n) {
            outWindow[s.charAt(right) - 'a']--;
            while (outWindow[0] < k || outWindow[1] < k || outWindow[2] < k) {
                outWindow[s.charAt(left) - 'a']++;
                left++;
            }
            // 滑动窗口外的字符是最终取走的字符,滑动窗口越长,需要取走的字符越少 
            ans = Math.max(ans, right - left + 1);
            right++;
        }
        return n - ans;
    }
}

复杂度分析

  • 时间复杂度:O(n),n 是 字符串s 的长度。
  • 空间复杂度:O(1)。
  • 13
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值