赞
踩
字节跳动2018秋招
有一个仅包含’a’和’b’两种字符的字符串s,长度为n,每次操作可以把一个字符做一次转换(把一个’a’设置为’b’,或者把一个’b’置成’a’);但是操作的次数有上限m,问在有限的操作数范围内,能够得到最大连续的相同字符的子串的长度是多少。
第一行两个整数 n , m (1<=m<=n<=50000),第二行为长度为n且只包含’a’和’b’的字符串s。
输出在操作次数不超过 m 的情况下,能够得到的 最大连续 全’a’子串或全’b’子串的长度。
示例1
8 1 aabaabaa
5
把第一个 'b' 或者第二个 'b' 置成 'a',可得到长度为 5 的全 'a' 子串。
这道题目是Leetcode 424题的特殊情况,可以用Leetcode424的方法完全解决,不需要用特殊的记录下a和b位置的方法
- #include <iostream>
- #include <vector>
- #include <string>
- using namespace std;
-
- int main()
- {
- int n,m;
- cin>>n>>m;
- string str;
- cin>>str;
- vector<int> Hash(2,0);
- int res = 0, maxNum = 0;
- for(int i=0,j=0;j<str.size();j++){
- Hash[str[j]-'a']++;
- maxNum = max(maxNum, Hash[str[j]-'a']);
- while(j-i+1-maxNum>m)
- Hash[str[i++]-'a']--;
- res = max(res,j-i+1);
- }
- cout<<res<<endl;
- }

2019 美团校招笔试题
时间限制:2秒
空间限制:131072K
给你一个01字符串,定义答案=该串中最长的连续1的长度,现在你有至多K次机会,每次机会可以将串中的某个0改成1,现在问最大的可能答案
输入描述:
输入第一行两个整数N,K,表示字符串长度和机会次数 第二行输入N个整数,表示该字符串的元素 ( 1 <= N <= 300000 , 0 <= K <= N )
输出描述:
输出一行表示答案
输入例子1:
10 2 1 0 0 1 0 1 0 1 0 1
输出例子1:
5
这一个题目是前面的再改造一下得到的,代码
- #include <iostream>
- #include <vector>
- #include <string>
- using namespace std;
- const int N = 300010;
- int num[N];
-
- int main()
- {
- int n,m;
- cin>>n>>m;
- for(int i=0;i<n;i++) cin>>num[i];
- vector<int> Hash(2,0);
- int res = 0, maxNum = 0;
- for(int i=0,j=0;j<n;j++){
- Hash[num[j]]++;
- maxNum = max(maxNum, Hash[1]); // 这里变为区间中1的个数
- while(j-i+1-maxNum>m)
- Hash[num[i++]]--;
- res = max(res,j-i+1);
- }
- cout<<res<<endl;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。