ในปัญหานี้ เราได้รับสตริง str โดยผู้ใช้ และเราต้องพิมพ์เฉพาะอักขระที่มีความถี่เป็นเลขคี่เท่านั้น
ในการแก้ปัญหานี้ เราต้องหาความถี่รวมของการเกิดอักขระในสตริง และพิมพ์เฉพาะอักขระของสตริงที่มีความถี่การเกิดคี่เท่านั้น
มาดูตัวอย่างเพื่อทำความเข้าใจหัวข้อกันดีกว่า −
Input : adatesaas. Output : dte
คำอธิบาย −อักขระที่มีความถี่ของการเกิดคือ −
| a | 4 |
| d | 1 |
| t | 1 |
| จ | 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