Check anagrams

/**

  • Determines if 2 strings are anagrams of each other, meaning that they both contain all of the same letters
  • Returns 1 if the strings are anagrams, 0 otherwise
  • Note: The function only checks lower case letters from 'a' to 'z'. No other characters will be given as input
  • Example: "test" and "etts" should return 1, "car" and "cat" should return 0
  • @param char * str1 (only contains lower case characters)
  • @param char * str2 (only contains lower case characters)
  • @return 1 if two strings are anagrams, 0 if they are not
    */
int checkAnagram(char* str1, char* str2) {
    //check to see if both strings are NULL
    if(str1 == NULL && str2 == NULL){
        return 1;
    }
    
    //find lengths of both strings
    int len1 = mystrlen(str1);
    int len2 = mystrlen(str2);

    if(len1 != len2){
        return 0;
    }
    
    //initialize array of size 26 to represent the letters of the alphabet and set all values to 0
    //Eg: alphabet[0] corresponds to 'a' , alphabet[1] corresponds to 'b'
    int alphabet[26]={0};

    //change values in alphabet array as they appear in the input strings
    int i = 0;
    for(i = 0; i < len1; i++){
        alphabet[str1[i] - 'a']++;
        alphabet[str2[i] - 'a']--;  //should be --
    }

    //check to see if all elements in the array are still 0
    for(i = 0; i < 26; i++){
        if(alphabet[i] !=  0){ 
            return 0;        
        }
    }
    return 1;
}

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    张土汪阅读 10,571评论 0 32
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 1,656评论 0 0
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 6,537评论 0 6
  • 最近的工作中,总有小伙伴因为 git 问题整天抓头发.一般我都是建议他们看 廖雪峰的 git, 说实话,廖老师的文...
    悟道皆空阅读 124评论 0 1
  • 在我的小年纪里我就想 有天我会走出暖红色的小镇 离开温暖舒适的家乡 寻找那抹心尖儿上的梦想 那味道对我而言 是无法...
    坛话儿阅读 36评论 2 1