2022.03.24携程后端前端第三题

严正声明:转载请注明出处!!!

题目描述:

游游拿到了一个仅包含小写字母的字符串。游游想截取一段连续子串,需要保证孩子该子串不同的字母种类不超过k个。

游游想知道,这个子串长度的最大值是多少?

输入描述:

第一行输入两个正整数n和k,分别代表字符串长度、需要保证的字母种类最大数量。

第二行输入一个长度为n的,只包含小写字母的字符串。

1 ≤ n ≤ 200000
1 ≤ k ≤ 26

输出描述:

子串长度的最大值

示例1:

输入

5 3
aabcd

输出

4

解法1:

import java.util.HashMap;
import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // 字符串的长度
        int n = sc.nextInt();
        // 字串不同的字母种类不超过k个
        int k = sc.nextInt();
        String s = sc.next();
        HashMap<Character, Integer> map = new HashMap<>();
        int res = 0;
        int i = 0;
        for(int j = 0;j < n;j++){
            if(map.containsKey(s.charAt(j))){
                map.put(s.charAt(j), map.get(s.charAt(j)) + 1);
            }else{
                map.put(s.charAt(j), 1);
            }
            while (map.size() > k){
                map.put(s.charAt(i), map.get(s.charAt(i)) - 1);
                if(map.get(s.charAt(i)) == 0){
                    map.remove(s.charAt(i));
                }
                i++;
            }
            res = Math.max(res, j - i + 1);
        }
        System.out.println(res);

    }
}

解法2:

import java.util.Scanner;

public class Test{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();

        String s = sc.next();

        int[] count = new int[26];
        int type=0;
        int res=0;
        int i=0;
        for (int j = 0; j < s.length(); j++) {
            char c = s.charAt(j);
            if (count[c-'a']==0){
                type++;
            }
            count[c-'a']++;

            while (type>k){
                char cc = s.charAt(i);
                count[cc - 'a']--;
                i++;
                if (count[cc - 'a']==0){
                    type--;
                }
            }
            res=Math.max(res,j-i+1);
        }
        System.out.println(res);

    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值