c++ - 查找字符在两个索引之间出现的次数
问题描述
我得到了一个输入字符串,它由一个基本字符串的 N 次重复组成。我需要在两个索引点之间找到“b”的出现。
string 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。希望能帮助到你。
推荐阅读
- python - 将本地图像上传到微软认知面孔
- nginx - nginx:根据标头值在请求中设置cookie
- macos - XQuartz/Xterm 中不允许 Catalina 操作
- node.js - 运行一个容器会停止另一个容器
- java - /someChars1@someChars2BOT 的正则表达式
- json - 从 JSON 数据中获取所有键和值
- javascript - JavaScript 箭头函数数组
- javascript - IONIC 5:将事件更改为可观察的问题
- webpack - 在 Next.js 中编译 npm 模块
- reactjs - 如何解决 Linux 中的“npm ERR!code ELIFECYCLE”错误?