import java.util.Arrays;
public class AnagramCheck {
/**
* Entry point: demonstrate the anagram check with a few examples.
* The goal is clarity, readability, and using the language's strengths.
*/
public static void main(String[] args) {
String a = "listen";
String b = "silent";
String c = "rail safety";
String d = "fairy tales";
String e = "hello";
String f = "world";
// Print results for each pair
System.out.println("listen vs silent: " + isAnagram(a, b));
System.out.println("rail safety vs fairy tales: " + isAnagram(c, d));
System.out.println("hello vs world: " + isAnagram(e, f));
}
/**
* Check whether two strings are anagrams.
*
* Steps:
* 1. Normalize both strings:
* - Remove whitespace
* - Convert to lowercase
* This ensures comparisons are fair and consistent.
*
* 2. Convert each normalized string to a char array.
*
* 3. Sort both arrays. If two strings contain the same letters
* in any order, their sorted forms will be identical.
*
* 4. Compare the sorted arrays using Arrays.equals.
*
* This approach is efficient, expressive, and easy to reason about.
*/
public static boolean isAnagram(String first, String second) {
// Normalize: remove spaces and unify case
String normalizedFirst = first.replaceAll("\\s+", "").toLowerCase();
String normalizedSecond = second.replaceAll("\\s+", "").toLowerCase();
// Quick length check: if lengths differ, they cannot be anagrams
if (normalizedFirst.length() != normalizedSecond.length()) {
return false;
}
// Convert to char arrays
char[] firstChars = normalizedFirst.toCharArray();
char[] secondChars = normalizedSecond.toCharArray();
// Sort both arrays
Arrays.sort(firstChars);
Arrays.sort(secondChars);
// Compare sorted arrays
return Arrays.equals(firstChars, secondChars);
}
}
/*
run:
listen vs silent: true
rail safety vs fairy tales: true
hello vs world: false
*/