Java Online Compiler
Example: Anagram Checker (Frequency Array) in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Anagram Checker (Frequency Array) import java.util.Scanner; // Main class containing the entry point of the program public class Main { /** * Checks if two strings are anagrams using a frequency array. * Ignores case and non-alphabetic characters. * Assumes ASCII characters for array size. * * @param str1 The first string. * @param str2 The second string. * @return true if the strings are anagrams, false otherwise. */ public static boolean areAnagramsUsingFrequencyArray(String str1, String str2) { // Step 1: Handle null or empty strings if (str1 == null || str2 == null) { return false; } if (str1.isEmpty() && str2.isEmpty()) { return true; } // Step 2: Normalize strings (remove spaces, convert to lowercase) String processedStr1 = str1.replaceAll("\\s", "").toLowerCase(); String processedStr2 = str2.replaceAll("\\s", "").toLowerCase(); // Step 3: Check if lengths are different after processing if (processedStr1.length() != processedStr2.length()) { return false; } // Step 4: Create a frequency array for characters (assuming ASCII) // Size 256 for all possible ASCII character values int[] charCounts = new int[256]; // Step 5: Iterate through the first string and increment character counts for (char c : processedStr1.toCharArray()) { charCounts[c]++; } // Step 6: Iterate through the second string and decrement character counts for (char c : processedStr2.toCharArray()) { charCounts[c]--; } // Step 7: Check if all character counts are zero // If they are, it means all characters matched in frequency for (int count : charCounts) { if (count != 0) { return false; // Mismatch found } } // All counts are zero, so they are anagrams return true; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("--- Anagram Checker (Frequency Array Method) ---"); System.out.print("Enter first string: "); String s1 = scanner.nextLine(); System.out.print("Enter second string: "); String s2 = scanner.nextLine(); boolean isAnagram = areAnagramsUsingFrequencyArray(s1, s2); if (isAnagram) { System.out.println("\"" + s1 + "\" and \"" + s2 + "\" are anagrams."); } else { System.out.println("\"" + s1 + "\" and \"" + s2 + "\" are NOT anagrams."); } scanner.close(); } }
Output
Clear
ADVERTISEMENTS