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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,775評論 0 33
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc閱讀 2,936評論 0 0
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa閱讀 8,925評論 0 6
  • 最近的工作中,總有小伙伴因為 git 問題整天抓頭發(fā).一般我都是建議他們看 廖雪峰的 git, 說實話,廖老師的文...
    悟道皆空閱讀 420評論 0 1
  • 在我的小年紀(jì)里我就想 有天我會走出暖紅色的小鎮(zhèn) 離開溫暖舒適的家鄉(xiāng) 尋找那抹心尖兒上的夢想 那味道對我而言 是無法...
    壇話兒閱讀 129評論 2 1