Java – the best solution for anagram checking?

I'm going through a permutation / crossword problem and want to enter the most effective check method@ H_ 403_ 7@ now, I'm doing this on Java land, so there's a library of everything, including sorting@ H_ 403_ 7@ the first way to check whether two strings are each other's puzzles is to check the length, sort them in some way, and then compare each index of the string The code is as follows:

private boolean validAnagram(String str,String pair) {
if(str.length() != pair.length()){
    return false;
}

char[] strArr = str.tocharArray();
char[] pairArr = pair.tocharArray();


Arrays.sort(strArr);
str = new String(strArr);

Arrays.sort(pairArr);
pair = new String(pairArr);

for(int i = 0; i<str.length(); i++){
    if(str.charAt(i) != pair.charAt(i)){
        return false;
    }
}
return true;
}

Or, I think it's easier to check against ASCII values and avoid checking every possible character The code is as follows:

private boolean validAnagram(String str,String pair) {
if(str.length() != pair.length()){
    return false;
}

char[] strArr = str.tocharArray();
char[] pairArr = pair.tocharArray();



int strValue = 0;
int pairValue = 0;

for(int i =0; i < strArr.length; i++){
    strValue+= (int) strArr[i];
    pairValue+= (int) pairArr[i];
}

if(strValue != pairValue){
    return false;
}
return true;
}

So, is this a better solution? I don't know much about what arrays gave me, but when I look around the old Internet, this is a more common answer Let me wonder if I missed anything

Solution

There are several ways to check whether two strings are puzzles@ H_ 403_ 7@ your question is, which is the better solution@ H_ 403_ 7 @ your first solution has sorting logic @ H_ 403_ 7 @ sorting has the worst case complexity (nlogn)@ H_ 403_ 7 @ your second logic uses only one complex loop @ H_ 403_ 7 @ up)

So in these two, your second solution is only O (n) @ H_ 403_ 7@ complexity will be a better solution than the first

One possible solution:

private boolean checkAnagram(String stringOne,String stringTwo){
        char[] first = stringOne.toLowerCase().tocharArray(); 
        char[] second = stringTwo.toLowerCase().tocharArray();
        // if length of strings is not same 
        if (first.length != second.length)
            return false;
        int[] counts = new int[26]; 
        for (int i = 0; i < first.length; i++){
            counts[first[i]-97]++;  
            counts[second[i]-97]--;   
        }
        for (int i = 0; i<26; i++)
            if (counts[i] != 0)
                return false;
        return true;
    }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>