How to check if two strings are anagrams (same letters, different words) in Java

2 Answers

0 votes
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

*/

 



answered Jan 28, 2019 by avibootz
edited Aug 20 by avibootz
0 votes
import java.util.Arrays;

public class Test {

    // Compare two char arrays without mutating the originals
    static boolean isAnagram(char[] s1, char[] s2) {

        // If lengths differ, they cannot be anagrams
        if (s1.length != s2.length) {
            return false;
        }

        // Copy arrays so the originals are not modified
        char[] a = Arrays.copyOf(s1, s1.length);
        char[] b = Arrays.copyOf(s2, s2.length);

        // Sort both copies
        Arrays.sort(a);
        Arrays.sort(b);

        // Compare sorted arrays
        return Arrays.equals(a, b);
    }

    public static void main(String[] args) {

        String st1 = "java";
        String st2 = "vaja";

        // Convert to char arrays
        char[] s1 = st1.toCharArray();
        char[] s2 = st2.toCharArray();

        if (isAnagram(s1, s2)) {
            System.out.println("Anagram");
        } else {
            System.out.println("Not Anagram");
        }
    }
}



/*
run:

Anagram

*/

 



answered Jan 28, 2019 by avibootz
edited Aug 20 by avibootz
...