查找字符在两个索引之间出现的次数
find the number of times a character occurs between two indexes
我得到了一个输入字符串,它由一个基本字符串的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。希望对您有所帮助。
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 数组索引的值没有增加
- int(c) 和 c-'0' 之间的区别。C++
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 在cuda线程之间共享大量常量数据
- 查找字符在两个索引之间出现的次数
- C++ 复制字符串的指定索引之间的任何子字符串
- 查找C++中两个索引之间的子字符串
- 在成员函数之间传递const变量为数组的索引
- 是否有C 功能来计算两个索引之间的距离
- 从 1 中创建新的字符 * 作为参数,元素位于 2 个索引之间
- 列表和向量的索引之间的差异
- 如何删除给定索引之间的所有元素
- String_view的索引运算符([])之间的差异
- C++数组运算符和 *(数组 + 索引)之间有什么区别(如果有)
- C++递归函数,可反转数组索引在两个边界之间的顺序
- 删除 2 个给定索引之间的元素的最佳算法
- 在两个索引之间反转向量的元素
- Java和JNI (dll)之间的索引超出边界异常
- 引用和数组索引之间的任何差异