滑動窗口(三)——Longest K unique characters substring(最長k個不同字符子串)

題目:

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)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章