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
");
gets(a);
gets(b);
if (check_anagram(a, b))
printf("The strings are anagrams.
");
else
printf("The strings aren't anagrams.
");
return 0;
}
int check_anagram(char a[], char b[]){
int first[26] = {0}, second[26] = {0}, c=0;
// Calculating frequency of characters of the first string
while (a[c] != '\0') {
first[a[c]-'a']++;
c++;
}
c = 0;
while (b[c] != '\0') {
second[b[c]-'a']++;
c++;
}
// Comparing the frequency of characters
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.
Advertisement
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP