字符频率等于给定字符串中其他字符频率之和的字符


介绍

C++字符串是由字母数字字符组成的流。字符串具有以下属性:

  • 字符串由一组固定的字符组成

  • 字符串位置默认从第0个索引开始

  • 任何字符的频率是指它在字符串中出现的次数。任何字符的频率范围可以从0(如果它没有出现)到字符串的长度。

在本文中,我们将开发一段代码,该代码将字符串作为输入,并检查任何字符的频率是否等于字符串中所有其他字符频率的总和。让我们来看下面的例子,以便更好地理解这个主题。

示例

示例1 - str - “@!ab@!”

输出 - True

例如,下面的示例字符串也包含特殊字符,其中每个字符的频率如下:

@ = 4

! = 2

a = 1

b = 1

因此,以下字符串具有以下适用属性:

freq(@) = freq(!) + freq(a) + freq(b)

4 = 2 + 1 + 1

在本文中,我们将创建一个解决方案来计算字符串中每个字符出现的次数,并进一步检查是否存在任何具有所需频率计数的字符。

语法

str.length()

length()

C++中的length()方法用于计算字符串中字符的个数。

算法

  • 接受输入字符串str

  • 创建一个包含26个字母的数组来存储字符的频率。它初始化为计数0,由freq数组指定。

  • 使用length()方法计算字符串的长度,用len表示。

  • 如果字符串的长度是奇数,则返回false标志。

  • 每次提取第i个位置的字符。

  • 此字符的频率加1。

  • 计算完整个字符串的长度后,检查频率数组。

  • 如果某个字符的频率等于其他字符频率的总和,则返回布尔标志值true。

示例

以下C++代码片段用于从给定的输入字符串中检查是否存在任何字符的出现次数等于所有字符的频率总和:

//including the required libraries
#include <bits/stdc++.h>
using namespace std;
 
//function to check if the frequency of occurrence of data is equivalent to other characters' frequency
bool charwithequalFreq(string str) {
   //storing the frequency of characters 
   int freq[26] = { 0 };
   //length of string 
   int len = str.length();
   //if the length of the string is odd 
   if (len % 2 == 1)
      return false;
 
   // Update the frequencies of the characters
   for (int i = 0; i < len; i++){
       char ch = str[i];
       freq[ch - 'a']+=1;
   }
        
 
   for (int i = 0; i < 26; i++)
      if (freq[i] == len / 2)
      {       
         cout<<"Holds true for character "<<(char)(i+'a') <<"\n";
         return true;
      }
   
   //none of the cases hold true
   return false;
}
//calling the frequency method
int main() {
    
   //input string
   string str = "tweeet";
 
   cout<< "Input String : "<<str<<"\n";
   //check the frquency 
   bool res = charwithequalFreq(str);
   if(!res){
      cout<<"There is no such character";
   }
   return 0;
}

输出

Input String : tweeet
Holds true for character e

结论

C++字符串中的字符位置默认从第0个索引开始。字符串是一种动态长度的存储结构,可以轻松地将字符追加任意次数。C++字符串中的每个字符都与一个计数相关联,由其频率表示。map数据结构非常有用,其中每个键都与一个确定的值相关联。

更新于:2023年7月31日

89 次查看

开启您的职业生涯

完成课程获得认证

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