以出现的顺序打印奇数频率的字符
在此问题中,用户给了我们字符串 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