a
、b
兩字串,輸出皆為兩者的子字串char a[1001] = {0};
char b[1001] = {0};
int i, j;
while(gets(a) && gets(b)){
int tableA[26] = {0};
int tableB[26] = {0};
for(i = 0; i < strlen(a); i++){
tableA[a[i] - 'a']++;
}
for(i = 0; i < strlen(b); i++){
tableB[b[i] - 'a']++;
}
...
}
for
迴圈由小到大遍歷字母表,透過 if
比較兩字串該字母出現的次數誰比較少,再用 for
輸出較少刺數的字母
for(i = 0; i < 26; i++){
if(tableA[i] != 0 && tableB[i] != 0){
if(tableA[i] <= tableB[i]){
min = tableA[i];
}
else{
min = tableB[i];
}
for(j = 0; j < min; j++){
printf("%c", i + 97);
}
}
}
#include<stdio.h>
#include<string.h>
int main(){
char a[1001] = {0};
char b[1001] = {0};
int i, j;
int length;
int min;
while(gets(a) && gets(b)){
int tableA[26] = {0};
int tableB[26] = {0};
for(i = 0; i < strlen(a); i++){
tableA[a[i] - 'a']++;
}
for(i = 0; i < strlen(b); i++){
tableB[b[i] - 'a']++;
}
for(i = 0; i < 26; i++){
if(tableA[i] && tableB[i]){
if(tableA[i] <= tableB[i]){
min = tableA[i];
}
else{
min = tableB[i];
}
for(j = 0; j < min; j++){
printf("%c", i + 97);
}
}
}
printf("\n");
}
return 0;
}