C++中重複字串中字元出現次數的計數


給定一個字串str、一個字元ch和一個正整數N。字串str無限重複。目標是找到在重複的第一個N個字元中字元ch出現的次數。

如果str是“abac”,字元是ch='b',N是10。

在“abacabacabacabac……”的前10個字元中,b出現兩次。

注意 − str和字元ch保持相同的形式(大小寫)。

讓我們透過例子來理解。

例如

輸入

str = "TPTTTT" ch = 'T' n = 12

輸出

Count of occurrences of a character in a repeated string are: 10

解釋

The number of ‘T’ in str is 5. Length of str is 6.
For n=12, str will be fully repeated twice, so count of Ts is 6*2=12.

輸入

str = "sets" ch = 's' n = 15

輸出

Count of occurrences of a character in a repeated string are: 7

解釋

The number of ‘s’ in str is 2. Length of str is 4.
For n=15, str will be fully repeated 3 times (first 12 characters), so count of s in those will be 3*2=6. For the remaining 3 characters (set) s occurs once. So count is 6+1=7

下面程式中使用的方案如下

在這個方案中,我們將首先計算字元ch在str中出現的次數。然後我們將str的長度除以N。我們將透過(N / str的長度)得到str在N個字元內的完整重複次數。因此,ch在這些重複中的出現次數將是簡單的乘法。對於剩餘的字元(N % str的長度),再次計算str中ch的個數,並新增到之前的計數中。

  • 取一個字串str。

  • 取n為整數,ch為字元,str的長度為整數。

  • 函式occurrences_char(string str, int length, int n, char ch)接收str、ch、n和str的長度,並返回在重複字串str的第一個n個字元中ch的計數。

  • 將初始計數設為0。

  • 使用for迴圈計算ch在str中出現的次數。對於每個str[i]==ch,遞增計數。

  • str在n中的重複次數為occ= n / length。

  • ch在這些重複中的出現次數將是count * occ。

  • 對於str剩餘的n % length個字元,檢查是否str[i]==ch,如果是,則遞增計數。

  • 返回計數作為結果。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int occurrences_char(string str, int length, int n, char ch){
   int count = 0;
   for (int i = 0; i < length; i++){
      if (str[i] == ch){
         count++;
      }
   }
   int occ = n / length;
   count = count * occ;
   for (int i = 0; i < n % length; i++){
      if (str[i] == ch){
         count++;
      }
   }
   return count;
}
int main(){
   string str = "TPTTTT";
   char ch = 'T';
   int n = 12;
   int length = str.size();
   cout<<"Count of occurrences of a character in a repeated string are: "<<occurrences_char(str, length, n, ch);
   return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

Count of occurrences of a character in a repeated string are − 10

更新於:2021年1月5日

6K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.