Unofficial C Solution to Problem 1.3 in Cracking the Coding Interview (5th Edition)
5 Feb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | // Author: Sheng Yu // Time: 02/05/2013 // // C solution for problem 1.3 in Cracking the Coding Interview 5th eidtion. // // Test environment: gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-52) // #include <stdio.h> #include <string.h> #include <stdbool.h> bool isAnagram(char *str1, char *str2){ // Check whether str1 and str2 are anagram // Works well for ASCII strings with length less than 2^16 // For longer string, overflow might happen int count[256]; int index = -1; if(strlen(str1) != strlen(str2)) return false; memset(count,0,256*sizeof(int)); // Scan str1, get its letters' distribution while(str1[++index] != ' '){ ++count[(unsigned int)str1[index]]; } // Scan str2, and compare its letters' distribution with str1 index = -1; while(str2[++index] != ' '){ --count[(unsigned int)str2[index]]; } index = -1; while( ++ index < 256){ if( count[index] != 0 ) return false; } return true; } int main(int argc, char *argv[]){ if(argc != 3){ printf("Invalid arguments.n"); return 1; } if(isAnagram(argv[1],argv[2])){ printf("They are anagram:nt%snt%sn",argv[1],argv[2]); } else{ printf("They are not anagram.nt%snt%sn",argv[1],argv[2]); } return 0; } |