18. Checking whether two strings are anagrams

Two strings that have the same characters, but that are in a different order, are anagrams. Some definitions impose that anagrams are case-insensitive and/or that white spaces (blanks) should be ignored.

So, independent of the applied algorithm, the solution must convert the given string into lowercase and remove white spaces (blanks). Besides that, the first solution we mentioned sorts the arrays via Arrays.sort() and will check their equality via Arrays.equals().

Once they are sorted, if they are anagrams, they will be equal (the following diagram shows two words that are anagrams):

This solution (including its Java 8 functional style version) is available in the code bundled with this book. The main drawback of these two solutions is represented by the sorting part. The following solution eliminates this step and relies on an empty array (initially containing only 0) of 256 indexes (extended ASCII table codes of characters—more information can be found in the Finding the first non-repeated character section).

The algorithm is pretty simple:

  • For each character from the first string, this solution increases the value in this array corresponding to the ASCII code by 1
  • For each character from the second string, this solution decreases the value in this array corresponding to the ASCII code by 1

The code is as follows:

private static final int EXTENDED_ASCII_CODES = 256;
...
public static boolean isAnagram(String str1, String str2) {

int[] chCounts = new int[EXTENDED_ASCII_CODES];
char[] chStr1 = str1.replaceAll("\s",
"").toLowerCase().toCharArray();
char[] chStr2 = str2.replaceAll("\s",
"").toLowerCase().toCharArray();

if (chStr1.length != chStr2.length) {
return false;
}

for (int i = 0; i < chStr1.length; i++) {
chCounts[chStr1[i]]++;
chCounts[chStr2[i]]--;
}

for (int i = 0; i < chCounts.length; i++) {
if (chCounts[i] != 0) {
return false;
}
}

return true;
}

At the end of this traversal, if the given strings are anagrams, then this array contains only 0.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset