查找字符在两个索引之间出现的次数

find the number of times a character occurs between two indexes

本文关键字:之间 索引 两个 字符 查找      更新时间:2023-10-16

我得到了一个输入字符串,它由一个基本字符串的N次重复组成。 我需要找到两个索引点之间出现"b"的位置。

字符串 mystr="ababba" 重复次数 = 1000 , 查找两个索引之间出现的"b",例如 120 和 250。

我不能使用蛮力,我递增到 120,然后计算"b"的数量直到结束索引,这对于大型输入字符串来说是超时的。

我已经计算并存储了 b 在 6 个字符的字符串"ababba"中的出现次数为 3。 我该如何继续?

for( auto& each : mystr)
{
if (each == 'b')
cntb++;
}

试试这个:

#include <iostream>
#include <cstring>
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main()
{
char inputString[11];
int b_in_string, b_occurrence, repetitions, startIndex, endIndex, actual_needed_count;
cout<<"Input string: ";
cin>>inputString;
cout<<"Repetitions: ";
cin>>repetitions;
cout<<"Start index: ";
cin>>startIndex;
cout<<"End index: ";
cin>>endIndex;
if(endIndex < startIndex)
{
cout<<"End index must be larger than start index. Program terminated.";
return 1;
}
b_in_string = 0;
b_occurrence = 0;
for(int i = 0; i < sizeof(inputString); i++)
{
if(inputString[i] == 'b')
{
b_in_string++;
}
}
actual_needed_count = endIndex - startIndex + 1; //start and end indexes inclusive
b_occurrence = b_in_string * actual_needed_count;
cout<<"Number of times 'b' occurs: ";
cout<<b_occurrence;
return 0;
}

它适用于 https://www.onlinegdb.com/online_c++_compiler。希望对您有所帮助。