什么是C语言的字谜?
字谜字符串只不过是在另一个字符串中出现相同次数的所有字符,我们称之为字谜。
用户输入两个字符串。我们需要计算每个字母(“a”至“z”)出现在其中的次数,然后比较它们相应的计数。字符串中字母的出现频率是它出现在其中的次数。
如果两个字符串对特定字母的频率计数相同,那么我们可以说这两个字符串是字谜。
例子1
字符串1-abcd
字符串2-bdac
这两个字符串具有相同的字母,仅出现一次。因此,这两个字符串是字谜。
例子2
字符串1-programming
字符串2-gramming
输出-字符串不是字谜。
示例
以下是字谜的C程序-
#include <stdio.h>
int check_anagram(char [], char []);
int main(){
char a[1000], b[1000];
printf("Enter two strings\n");
gets(a);
gets(b);
if (check_anagram(a, b))
printf("The strings are anagrams.\n");
else
printf("The strings aren't anagrams.\n");
return 0;
}
int check_anagram(char a[], char b[]){
int first[26] = {0}, second[26] = {0}, c=0;
// 计算第一个字符串的字符频率
while (a[c] != '\0') {
first[a[c]-'a']++;
c++;
}
c = 0;
while (b[c] != '\0') {
second[b[c]-'a']++;
c++;
}
// 比较字符的出现次数
for (c = 0; c < 26; c++)
if (first[c] != second[c])
return 0;
return 1;
}输出结果
执行以上程序后,将产生以下输出-
Run 1: Enter two strings abcdef deabcf The strings are anagrams. Run 2: Enter two strings tutorials Point The strings aren't anagrams.
作者头像
作者名称
作者性别



评论列表