finding if two words are anagrams of each other

后端 未结 22 1290
隐瞒了意图╮
隐瞒了意图╮ 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:18

    Get table of prime numbers, enough to map each prime to every character. So start from 1, going through line, multiply the number by the prime representing current character. Number you'll get is only depend on characters in string but not on their order, and every unique set of characters correspond to unique number, as any number may be factored in only one way. So you can just compare two numbers to say if a strings are anagrams of each other.

    Unfortunately you have to use multiple precision (arbitrary-precision) integer arithmetic to do this, or you will get overflow or rounding exceptions when using this method.
    For this you may use libraries like BigInteger, GMP, MPIR or IntX.

    Pseudocode:

    prime[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101}
    
    primehash(string)
        Y = 1;
        foreach character in string
            Y = Y * prime[character-'a']
    
        return Y
    
    isanagram(str1, str2)
        return primehash(str1)==primehash(str2)
    

提交回复
热议问题