finding if two words are anagrams of each other

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

    Code to find whether two words are anagrams:

    Logic explained already in few answers and few asking for the code. This solution produce the result in O(n) time.

    This approach counts the no of occurrences of each character and store it in the respective ASCII location for each string. And then compare the two array counts. If it is not equal the given strings are not anagrams.

    public boolean isAnagram(String str1, String str2)
    {
        //To get the no of occurrences of each character and store it in their ASCII location
        int[] strCountArr1=getASCIICountArr(str1);
        int[] strCountArr2=getASCIICountArr(str2);
    
        //To Test whether the two arrays have the same count of characters. Array size 256 since ASCII 256 unique values
        for(int i=0;i<256;i++)
        {
            if(strCountArr1[i]!=strCountArr2[i])
                return false;
        }
        return true;
    }
    
    public int[] getASCIICountArr(String str)
    {
        char c;
        //Array size 256 for ASCII
        int[] strCountArr=new int[256];
        for(int i=0;i

提交回复
热议问题