finding if two words are anagrams of each other

后端 未结 22 1318
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 14:51

I am looking for a method to find if two strings are anagrams of one another.

Ex: string1 - abcde
string2 - abced
Ans = true
Ex: string1 - abcde
string2 - ab         


        
22条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 15:05

    It seems that the following implementation works too, can you check?

    int histogram[256] = {0};
    for (int i = 0; i < strlen(str1); ++i) {
       /* Just inc and dec every char count and
        * check the histogram against 0 in the 2nd loop */
       ++histo[str1[i]];
       --histo[str2[i]];
    }
    
    for (int i = 0; i < 256; ++i) {
       if (histo[i] != 0)
         return 0; /* not an anagram */
    }
    
    return 1; /* an anagram */
    

提交回复
热议问题