以出現的順序列印奇數頻率的字元
在此問題中,使用者給了我們字串 str。我們只需要列印僅出現次數為奇數的字元。
要解決此問題,我們必須計算一個字元在字串中的出現總次數。並且僅打印出現次數為奇數的字串字元。
我們舉一個例子,以便更好地理解這個主題 −
Input : adatesaas. Output : dte
說明 −帶有其出現頻率的字元為 −
| a | 4 |
| d | 1 |
| t | 1 |
| e | 1 |
| s | 2 |
出現次數為奇數的字元是 d、t、e。
演算法
現在我們嘗試建立一個演算法來解決此問題 −
Step 1 : Traverse the string and count the number of occurrences on characters of the string in an array. Step 2 : Traverse the frequency array and print only those characters whose frequency of occurrence is odd.
示例
我們基於此演算法建立一個程式 −
#include <bits/stdc++.h>
using namespace std;
int main(){
string str = "asdhfjdedsa";
int n = str.length();
int frequency[26];
memset(frequency, 0, sizeof(frequency));
for (int i = 0; i < n; i++)
frequency[str[i] - 'a']++;
for (int i = 0; i < n; i++) {
if (frequency[str[i] - 'a'] % 2 == 1) {
cout << str[i]<<" , ";
}
}
return 0;
}輸出
d , h , f , j , d , e , d
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP