C++中統計具有相同數量的0、1和2的子字串


給定一個只包含0、1和2的字串str。目標是找到str的所有子字串,這些子字串具有相同數量的0、1和2。如果str是“12012”,則具有相同數量的0、1和2的子字串將是“120”、“201”和“012”。計數將為3。

讓我們透過示例來理解。

輸入 − str=”112200120”

輸出 −具有相同數量的0、1和2的子字串個數為− 5

說明 − 子字串將是...

str[0-5]=”112200”, str[1-6]=”122001”, str[5-7]=”012”, str[6-8]=”120”, str[7-0]=”201”

輸入 − str=”12012”

輸出 −具有相同數量的0、1和2的子字串個數為:3

說明 − 子字串將是 −

str[0-2]=”120” , str[1-3]=”201”, str[2-4]=”012”

下面程式中使用的方法如下:

  • 獲取一個整數型別的字串並計算字串的長度。

  • 將資料傳遞給函式進行進一步處理。

  • 使用一個名為count的臨時變數來儲存具有相同數量的0、1和2的子字串的計數。

  • 建立一個map型別的變數,它將鍵值對對映到給定數字的頻率。

  • 在鍵值對(0,0)處儲存1,並從0到字串長度開始迴圈。

  • 在迴圈內,檢查IF str[i] = 0,則增加0的計數;ELSE IF str[i] = 1,則增加1的計數;ELSE增加2的計數。

  • 將0和1設定為0 - 1和0,將0和2設定為0 - 2。

  • 建立一對zero_one和zero_two,並將計數設定為count + map_pair的差值(透過建立鍵值對計算得出)。

  • 將map_pair加1。

  • 返回count。

  • 列印結果。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int count_string(string str_1, int length_str1, string str_2, int length_str2){
   int count = INT_MAX;
   int arr_1[26] = { 0 };
   int arr_2[26] = { 0 };
   for (int i = 0; i < length_str1; i++){
      arr_1[str_1[i] - 'a']++;
   }
   for (int i = 0; i < length_str2; i++){
      arr_2[str_2[i] - 'a']++;
   }
   int alphabets = 26;
   for (int i = 0; i < alphabets; i++){
      if(arr_2[i]){
         count = min(count, arr_1[i] / arr_2[i]);
      }
   }
   return count;
}
int main(){
   string str_1 = "knowledge", str_2 = "know";
   int length_str1 = str_1.size();
   int length_str2 = str_2.size();
   cout<<"Count occurrences of a string that can be constructed from another given string are: "<<count_string(str_1,length_str1, str_2, length_str2);
   return 0;
}

輸出

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

Count of Substrings with equal number of 0s, 1s and 2s are: 1

更新於:2020年12月1日

瀏覽量:299

開啟你的職業生涯

完成課程獲得認證

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