Skip to content

Instantly share code, notes, and snippets.

@jsbonso
Created October 14, 2017 08:20
Show Gist options
  • Save jsbonso/27ee66647cce5385104f7209018aba85 to your computer and use it in GitHub Desktop.
Save jsbonso/27ee66647cce5385104f7209018aba85 to your computer and use it in GitHub Desktop.
Java - Check if 2 strings are an Anagram of each other
/**
* Check if the two strings are an anagram of each other.
* For example: LISTEN is an Anagram of SILENT.
*
* Two strings are an anagram of each other if the characters
* and the numbers of characters that are composing them,
* are exactly the same. So for example, SUE and USE are anagrams
* because both words have one E, one S and one U,
* hence: ESU = ESU.
*
* "The Eyes" and "They see" are anagrams as both phrases
* have three E's, one H, one S, one T and one Y.
* If you format them to be on either lower or upper case and arranged
* the characters in alphabetical order of these 2 phrases,
* then, you can easily perform a comparison using an equal method
* hence: EEEHSTY = EEEHSTY
*
* @param input1
* @param input2
* @return boolean
*/
static boolean isAnagram(String input1, String input2) {
// 1. Transform the parameters as char arrays
char[] input1Array = input1.toLowerCase().toCharArray();
char[] input2Array = input2.toLowerCase().toCharArray();
// 2. Arrange the characters in alphabetical order
Arrays.sort(input1Array);
Arrays.sort(input2Array);
// 3. Compare the generated strings if they are the same.
return Arrays.equals(input1Array, input2Array);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment