变位词字符串实际上是指另一个字符串中出现相同次数的所有字符,我们称之为变位词。
用户输入两个字符串。我们需要计算每个字母(’a’到’z’)在它们中出现的次数,然后比较它们对应的计数。字母在字符串中出现的频率是它在其中出现的次数。
如果两个字符串具有相同的特定字母频率计数,则可以说这两个字符串是变位词。
示例1
字符串1 – abcd
立即学习“C语言免费学习笔记(深入)”;
字符串2 – bdac
这两个字符串具有相同的只出现一次的字母。因此,这两个字符串是变位词。
示例2
字符串1 – programming
字符串2 – gramming
输出 – 这两个字符串不是变位词。
示例
以下是一个变位词的C程序 –
#include 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] != '') { first[a[c]-'a']++; c++; } c = 0; while (b[c] != '') { second[b[c]-'a']++; c++; } // Comparing the frequency of characters for (c = 0; c
输出
执行上述程序时,会产生以下输出 -
Run 1:Enter two stringsabcdefdeabcfThe strings are anagrams.Run 2:Enter two stringstutorialsPointThe strings aren't anagrams.登录后复制
以上就是什么是C语言中的变位词(anagram)?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2582593.html