滑动窗口(三)——Longest K unique characters substring(最长k个不同字符子串)

该博客介绍了如何找到给定字符串中最长的包含恰好k个不同字符的子串。通过使用滑动窗口方法,并在遇到不满足k个独特字符条件时处理特殊情况,可以实现O(N)的时间复杂度解决方案。文章提供了输入输出示例及代码分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

Given a string you need to print the size of the longest possible substring that has exactly k unique characters. If there is no possible substring print -1. Example For the string aabacbebebe and k = 3 the substring will be cbebebe with length 7.

Input: The first line of input contains an integer T denoting the no of test cases then T test cases follow. Each test case contains two lines . The first line of each test case contains a string s and the next line conatains an integer k.

Output: For each test case in a new line print the required output.

Constraints: 1<=T<=100 1<=k<=10

Example: Input: 2 aabacbebebe 3 aaaa 1 Output: 7 4

代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class GFG {
    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());
        while(t-->0){
            String str = br.readLine();
            int k = Integer.parseInt(br.readLine());
            int len = str.length();
            int [] arr = new int[26];
            int dis=0;
            int start=0;
            int maxLen=-1;
            for(int i=0;i<len;i++){
                if(arr[str.charAt(i)-'a']==0){
                    dis++;
                }
                arr[str.charAt(i)-'a']++;
                while(dis>k){
                    arr[str.charAt(start)-'a']--;
                    if(arr[str.charAt(start)-'a']==0){
                        dis--;
                    }
                    start++;
                }
                if(dis==k&&maxLen<i-start+1){
                    maxLen=i-start+1;
                }
            }
            System.out.println(maxLen);
        }
    }
}

分析:

这道题和滑动窗口(二)有点像,但比它稍微复杂点,首先也是用个arr存同种类的字符,然后滑动窗口,不同的是,这里如果匹配不到k个不同字符串,则输出-1,所以处理与前一篇略有不同.

时间复杂度同样是O(N)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值