char数组如何用于识别字谜?

时间:2015-07-07 04:07:11

标签: c anagram

我正在尝试编写一个anagram程序,所以我找到了以下示例。但我无法弄清楚这一行,first[a[i]-'a']++;这里增加这个char数组的值是什么意思?

#include <stdio.h>
int check_anagram(char a[], char b[]){
   int first[26] = {0}, second[26] = {0}, i = 0;

   while (a[i] != '\0'){
      first[a[i]-'a']++;   //  ??????????
      i++;
   }
   i = 0;
   while (b[i] != '\0'){
      second[b[i]-'a']++;
      i++;
   }
   for (i = 0; i < 26; i++){
      if (first[i] != second[i])
         return 0;
   }
   return 1;
}

int main(){
   char a[100], b[100];
   int flag;

   printf("Enter first string\n");
   gets(a);
   printf("Enter second string\n");
   gets(b);

   flag = check_anagram(a, b);
   if (flag == 1)
      printf("\"%s\" and \"%s\" are anagrams.\n", a, b);
   else
      printf("\"%s\" and \"%s\" are not anagrams.\n", a, b);

   return 0;
}

2 个答案:

答案 0 :(得分:5)

first[]second[]是包含分别出现在第一个和第二个字符串中的字母数的数组。

所以first[a[i]-'a']++正在递增给定字母的计数。最初,所有字母(索引0 - 25,对应于字母a-z)将具有count = 0.当您逐步浏览字符串中的每个字母时,您将增加该特定字母的计数。

结果是整个单词的{strong> histogram letter frequencies

对两个字符串(a和b)中的每个字符串执行此操作可以让您判断它们是否是彼此的字谜:任何一对字符串都是相同的直方图。

示例:

""         -> [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
"CAT"      -> [1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0]
"ESTRANGE" -> [1,0,0,0,2,0,1,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,0,0,0]
"SERGEANT" -> [1,0,0,0,2,0,1,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,0,0,0] // same as "ESTRANGE"

答案 1 :(得分:1)

该行

  first[a[i]-'a']++;

假设a[i]的值在a-z范围内。当a[i]a时,它会增加first[0]。当a[i]z时,它会增加first[25]。到循环结束时

while (a[i] != '\0'){
  first[a[i]-'a']++;   //  ??????????
  i++;
}

数组first包含数组a-z中字母a的计数。