이 문제에서 우리는 사용자로부터 문자열 str을 받습니다. 그리고 발생 빈도가 홀수인 문자만 인쇄해야 합니다.
이 문제를 해결하려면 문자열에서 문자의 총 발생 빈도를 찾아야 합니다. 그리고 발생 빈도가 홀수인 문자열만 출력합니다.
주제를 더 잘 이해하기 위해 예를 들어 보겠습니다 -
Input : adatesaas. Output : dte
설명 −발생 빈도가 있는 문자는 다음과 같습니다. -
| a | 4 |
| d | 1 |
| t | 1 |
| e | 1 |
| 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