7.18 热身赛 Substring

Substring

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 999 Accepted Submission(s): 168

Problem Description

You are given a string S[1…N] containing only lowercase letters. Now you need to find the longest substring S[l…r] such that every letter (a to z) appears no more than K times in the substring. You just need to output the length (r−l+1) of the longest substring.

Input

There are multiple test cases.

Each test case contains one integer K (1≤K≤N) and one string S in one line.

It’s guaranteed that the sum of lengths of the input strings is no more than 4×105.

Output

For each test case, print one integer in one line, denoting the length of the longest substring.

Sample Input

1 abcabcabc
2 abcabcabc
2 aaabbbccc

Sample Output

3
6
4

大概题意

每行给个k,给个长度大于等于k的字符串s,求字符串s中a到z每个字母出现次数不超过k次的最长子串长度

思路

用map标记当前子串中各个字符的数量,用双指针截取子串。

代码

#include <iostream>
#include <cstdio>
#include <map>

using namespace std;
long long t, n, a, b;
string s;

int main() {
    while (cin >> a >> s) {
        map<char, int> x;
        int res = 0;
        for (int l = 0, r = 0; l < s.length(); ++l) {
            while (l <= r && r < s.length() && x[s[r]] < a) {
                x[s[r]]++;
                r++;
            }
            res = max(res, r - l);
            x[s[l]]--;
        }
        printf("%d\n", res);
    }

    return 0;
}
posted @   嘿,抬头!  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
点击右上角即可分享
微信分享提示