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