用 C++ 統計給定字串所有子串中母音字母的個數


給定一個包含英文字母的字串 str,目標是查詢 str 的所有子串中出現的母音字母的個數。如果字串是“abcde”,則子串將是“a”、“b”、“c”、“d”、“e”、“ab”、“bc”、“cd”、“de”、“abc”、“bcd”、“cde”、“abcd”、“bcde”、“abcde”。這些子串中母音字母的計數是 10。(a 和 e)

例如

輸入

str = ”aloe”

輸出

Count the number of vowels occurring in all the substrings of given string are:
14

解釋

The substrings are:
“a”, “l”, “o”, “e”, “al”, “lo”, “oe”, “alo”, “loe”, “aloe”. Total vowels in these are: 14

輸入

str=”http”

輸出

Count the number of vowels occurring in all the substrings of given string are:
0

解釋

The substrings are:
“h”, “t”, “t”, “p”, “ht”, “tt”, “tp”, “htt”, “ttp”, “http”. Total vowels in these are: 0

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

在此方案中,我們將建立一個向量 vec,它在 vec[i] 中儲存第 i 個字元在所有子串中出現的次數。

第 0 個字元出現在 n 個子串中,其中 n 是字串 str 的長度。

第 i 個字元出現在所有包含它的子串中(n−i)+ 包含第 i 個字元和前一個字元的子串數(arr[i−1])− 只由前一個字元組成的子串數(i)。

  • 將字串 str 作為輸入。

  • 函式 substring_vowels_count(string str, int length) 獲取帶有其長度的 str 並返回給定字串所有子串中出現的母音字母的個數。

  • 將初始計數設為 0。

  • 取一個整數向量 vec。

  • 使用 for 迴圈從 i=0 到 i<length 遍歷 vec,並使用 str 的所有子串中第 i 位置字元出現的次數填充它。

  • 如果 i=0,則對於第 0 個字元,此計數為 length。使用 push_back[length] 設定 vec[0]=length。

  • 對於所有其他字元,使用 push_back(temp_1 + temp_2) 設定,其中 temp_1=length−1 且 temp_2=vec[i−1]−i。

  • 現在再次使用 for 迴圈遍歷 str,對於每個 str[i] 作為母音(a、e、i、o 或 u),將 vec[i] 加到計數中。

  • 最後,我們將得到子串中母音出現的總數 count。

  • 返回 count 作為結果。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int substring_vowels_count(string str, int length){
   int count = 0;
   vector<int> vec;
   for (int i = 0; i < length; i++){
      if (i == 0){
         vec.push_back(length);
      } else {
         int temp_1 = length − i;
         int temp_2 = vec[i − 1] − i;
         vec.push_back(temp_1 + temp_2);
      }
   }
   for (int i = 0; i < length; i++){
      if(str[i] == 'a' || str[i] == 'i' || str[i] == 'e' || str[i] == 'o' || str[i] == 'u'){
         count = count + vec[i];
      }
   }
   return count;
}
int main(){
   string str = "honesty";
   int length = str.length();
   cout<<"Count the number of vowels occurring in all the substrings of given string are: "<<substring_vowels_count(str, length);
   return 0;
}

輸出

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

Count the number of vowels occurring in all the substrings of given string are: 28

更新於:2021年1月5日

381 次檢視

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告