用 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 次查看

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.