传送门:http://codeforces.com/contest/1105/problem/B
Given a string ss of length nn and integer kk (1≤k≤n1≤k≤n). The string ss has a level xx, if xx is largest non-negative integer, such that it's possible to find in ss:
- xx non-intersecting (non-overlapping) substrings of length kk,
- all characters of these xx substrings are the same (i.e. each substring contains only one distinct character and this character is the same for all the substrings).
A substring is a sequence of consecutive (adjacent) characters, it is defined by two integers ii and jj (1≤i≤j≤n1≤i≤j≤n), denoted as s[i…j]s[i…j]= "sisi+1…sjsisi+1…sj".
For example, if k=2k=2, then:
- the string "aabb" has level 11 (you can select substring "aa"),
- the strings "zzzz" and "zzbzz" has level 22 (you can select two non-intersecting substrings "zz" in each of them),
- the strings "abed" and "aca" have level 00 (you can't find at least one substring of the length k=2k=2 containing the only distinct character).
Zuhair gave you the integer kk and the string ss of length nn. You need to find xx, the level of the string ss.
The first line contains two integers nn and kk (1≤k≤n≤2⋅1051≤k≤n≤2⋅105) — the length of the string and the value of kk.
The second line contains the string ss of length nn consisting only of lowercase Latin letters.
Print a single integer xx — the level of the string.
8 2 aaacaabb
2
2 1 ab
1
4 2 abab
0
In the first example, we can select 22 non-intersecting substrings consisting of letter 'a': "(aa)ac(aa)bb", so the level is 22.
In the second example, we can select either substring "a" or "b" to get the answer 11.
题意概括:
给一串长度为 N 的字符,求长度为 K 的由相同单种字母组成的子串的最大数量。
解题思路:
单指针模拟长度为 K 的子串的起始点,O(N)遍历一遍整个字符,记录每种字母满足条件的子串所对应的数量。
AC code:
1 #include <bits/stdc++.h> 2 #define INF 0x3f3f3f3f 3 #define LL long long 4 using namespace std; 5 const int MAXN = 2e5+10; 6 char str[MAXN]; 7 int num[30]; 8 int main() 9 { 10 int N, K; 11 scanf("%d %d", &N, &K); 12 scanf("%s", str); 13 int len = strlen(str); 14 int st = 0; 15 bool flag; 16 while(st+K-1 < len){ 17 flag = true; 18 for(int i = st+1; i <= st+K-1; i++){ 19 //printf("%c %c ", str[i], str[i-1]); 20 if(str[i] != str[i-1]){ 21 flag = false; 22 st = i; 23 break; 24 } 25 } 26 if(flag){ 27 //printf("%d %c ",st, str[st]); 28 num[str[st]-'a']++; 29 st = st+K; 30 } 31 //st+=K; 32 } 33 int ans = 0; 34 for(int i = 0; i < 26; i++){ 35 //printf("%d %d ", i, num[i]); 36 ans = max(num[i], ans); 37 } 38 39 printf("%d ", ans); 40 return 0; 41 42 }