严正声明:转载请注明出处!!!
题目描述:
游游拿到了一个仅包含小写字母的字符串。游游想截取一段连续子串,需要保证孩子该子串不同的字母种类不超过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);
}
}