字元頻率等於給定字串中其他字元頻率之和的字元
介紹
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資料結構非常有用,其中每個鍵都與一個確定的值相關聯。
廣告