หาตัวอักษรที่ปรากฏน้อยที่สุดใน string (รวม case-sensitive)
ตรรกะ
1. นับ frequency ของแต่ละ ASCII character (0-255)
2. หาค่าที่ frequency > 0 และน้อยที่สุด
โปรแกรม
#include <stdio.h>
#define SIZE 100
#define CHARS 255
int main() {
char string[SIZE];
int frequency[CHARS] = {0};
int i = 0, minimum = 0, value;
printf("Enter the string: ");
gets(string); // หมายเหตุ: gets ไม่ปลอดภัย ควรใช้ fgets
while (string[i] != '\0') {
value = (int)string[i];
frequency[value]++;
i++;
}
for (i = 0; i < CHARS; i++) {
if (frequency[i] != 0) {
if (frequency[minimum] == 0 || frequency[i] < frequency[minimum])
minimum = i;
}
}
printf("Minimum occurrence character is '%c' = %d times.\n", minimum, frequency[minimum]);
return 0;
}
ผลลัพธ์
Enter the string: tutorialspoint
Minimum occurrence character is 'a' = 1 times.