比较每个字符串并找到所有字符串中常见的小写字母数。 每个字符串由从“a”到“z”的小写字母表示。
4
abcf
aghb
acbl
bamn
2 // a and b
#include<stdio.h>
#include<string.h>
int main() {
int n;
scanf("%d\n",&n);
char str[n][100];
char var[0][100];
for(int i=0; i<n; i++) { // strings
scanf("%99s/n",str[i]);
}
for(int i=0;i<100;i++) { // comparison of first 2 strings
for(int k=0;k<100;k++)
if(str[0][i]==str[1][k])
for(int j=0;j<strlen(str[0]);j++) {
var[0][j]=str[0][j]; // storing the common letters in a var array
}
}
for(int l=0; l<strlen(str[1]); l++) { // comparing letters in var array with the letters of all other strings
int x;
if(var[0][l]==str[l+2][l]);
x=strlen(var[0]); // counting the common letters
printf("%d\n",x);
}
return 0;
}
答案 0 :(得分:1)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
int n;
scanf("%d",&n);
char str[n][100];
char var[n][26];
memset(&var[0][0], 0, sizeof(var));
for(int i=0; i<n; i++) {
scanf("%99s", str[i]);
char ch;
for(int j=0; ch=str[i][j]; ++j){
if(islower(ch)){
var[i][ch-'a']=1;//depend on the sequence of character codes
}
}
}
int x = 0;
for(int i=0; i<26; ++i){
int num = 0;
for(int j=0;j<n;++j)
if(var[j][i])
++num;
if(num==n)//all string has character of ('a'+i)
++x;
}
printf("%d\n",x);
return 0;
}
答案 1 :(得分:0)
不确定为什么你会想要特殊情况下的前两个字符串?这样的方法怎么样(伪代码):
- create a set of characters, name it letters_in_all_strings
- add every lowercase letter to letters_in_all_strings
- for each input string
- create a set of characters, name it letters_in_this_string
- add every character in the input string to letters_in_this_string
- remove all letters from letters_in_all_strings that are not present in letters_in_this_string
- print out the size of letters_in_all_strings
您可以使用由char索引的0和1数组来在C中实现一组字符。或者您可以使用glib(https://stackoverflow.com/a/2502721/2186890)。或者考虑使用更现代的编程语言?