Substrings of size K with K distinct chars

Given a string s and an int k, return an int representing the number of substrings (not unique) of s with exactly k distinct characters. If the given string doesn't have k distinct characters, return 0.
https://leetcode.com/problems/subarrays-with-k-different-integers

Example 1:

Input: s = "pqpqs", k = 2
Output: 7
Explanation: ["pq", "pqp", "pqpq", "qp", "qpq", "pq", "qs"]

思路:这题思路很巧妙,我是看了上面那个 subarrays with k different integers 的花花视频才懂的。

直接求很难,但是我们可以转换成 f(k) - f(k-1)  f(k)表示最多不大于k(at most k)的char的string的个数, at most k, 可以用sliding window的双指针来做,count 就是 j - i,表示以j - 1 为尾巴的subarray的个数;

public class numberOfUniqueChars {
    public int getAtMostKCharacters(String s, int k) {
        if(s == null || s.length() == 0) {
            return 0;
        }

        int j = 0;
        int[] counts = new int[256];
        int c = 0;
        int ans = 0;
        for(int i = 0; i < s.length(); i++) {
            // move j;
            while(j < s.length() && c <= k) {
                if(counts[s.charAt(j)] == 0 ) {
                    if(c == k) {
                        break;
                    }
                    c++;
                }
                counts[s.charAt(j)]++;
                j++;
            }

            //update result;
            ans += j - i;

            // remove i;
            counts[s.charAt(i)]--;
            if(counts[s.charAt(i)] == 0) {
                c--;
            }
        }

        return ans;
    }

    public static void main(String[]  args) {
        /*
        *
        * Input: s = "pqpqs", k = 2
          Output: 7
          Explanation: ["pq", "pqp", "pqpq", "qp", "qpq", "pq", "qs"]
        * */
        numberOfUniqueChars numberOfUniqueChars = new numberOfUniqueChars();
        String s = "pqpqs";
        int ans1 = numberOfUniqueChars.getAtMostKCharacters(s, 2) - numberOfUniqueChars.getAtMostKCharacters(s, 1);
        // ans = 7;
        System.out.println("ans: " + ans1);

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值