首页 > 解决方案 > 查找字符在两个索引之间出现的次数

问题描述

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

string mystr="ababba" 重复次数 = 1000 ,找到两个索引之间出现的 'b',比如 120 和 250。

我不能使用蛮力将我的方式增加到 120,然后计算 'b' 的数量直到结束索引,这对于大输入字符串会超时。

我已经计算并将 b 在 6 个字符“ababba”的字符串中的出现存储为 3。我该如何进行?

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

标签: c++algorithm

解决方案


尝试这个:

#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。希望能帮助到你。


推荐阅读