
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print Characters Having Odd Frequencies in C++
In this problem, we are given string str by the user. And we have to print only those characters whose frequencies of occurrence in an odd number.
To solve this problem, we have to find the total frequency of occurrence of a character in a string. And print only those characters of the string that have odd frequencies of occurrence.
Let’s take an example to understand the topic better −
Input : adatesaas. Output : dte
Explanation −The characters with their frequency of occurrence are −
a | 4 |
d | 1 |
t | 1 |
e | 1 |
s | 2 |
Characters with odd frequency are d, t, e.
Algorithm
Now let's try to create an algorithm to solve this problem −
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.
Example
Let's create a program based on this algorithm −
#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; }
Output
d , h , f , j , d , e , d
Advertisements