C++ 中长度为 K 的由相同字符组成的子字符串的最大数量
给定任务是找到长度为 **K** 的由相同字符组成的子字符串的最大数量。给定一个字符串 s 和另一个整数 **K**,我们必须计算大小为 **K** 且具有相同字符的子字符串的出现次数。
在找到的子字符串中,我们必须选择出现次数最多的子字符串。
现在让我们用一个例子来理解我们必须做什么 -
输入
s = ”tuuxyyuuc”, K = 2
输出
2
解释
这里长度为 2 且具有相同字符的子字符串是:“uu” 和 “yy”,但如所见,“yy” 只出现 1 次,“uu” 出现 2 次。因此,输出变为 2。
输入
s = “hhigggff”, K = 3
输出
1
下面程序中使用的方法如下
在 Max() 函数中,初始化 int ans = 0 来存储最终答案,size = str.size() 来存储字符串的大小,并声明 char c 来存储我们需要检查的字符。
从 j = 0 循环到 j < 26,并将 c = ‘a’ + j 设置为我们将检查每个字符。
初始化变量 int CurrCh = 0 用于存储包含当前字符的子数组的出现次数。
从 i = 0 循环到 i <= size – K,并检查 if (str[i] != c)。如果是,则添加 continue; 语句。
初始化 count = 0 来存储当前字符的子数组的长度。
创建一个 while 循环,条件为 (i < size && count != K && str[i] == c),并在循环内部递增 i 和 **count**。在 while 循环外部将 i 减 1。
检查 if (count == K)。如果是,则递增 **CurrCh**。
关闭第二个 For 循环,并通过设置 ans = max(ans, CurrCh) 来更新 **ans** 的值。
最后关闭第一个 For 循环并返回 **ans**。
示例
#include <bits/stdc++.h>
using namespace std;
int Max(string str, int K){
int ans = 0, size = str.size();
char c;
//Checking for all characters
for (int j = 0; j < 26; j++){
c = 'a' + j;
//checking for current character
int CurrCh = 0;
for (int i = 0; i <= size - K; i++){
if (str[i] != c)
continue;
//Counting the size of sub-string
int count = 0;
while (i < size && count != K && str[i] == c){
i++;
count++;
}
i--;
//Increment CurrCh if sub-string has length K
if (count == K)
CurrCh++;
}
//Update ans
ans = max(ans, CurrCh);
}
return ans;
}
//main function
int main(){
string str = "tuuuxyuuu";
int K = 3;
cout << Max(str, K);
return 0;
}输出
2
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP