|
| 1 | +import java.util.Scanner; |
| 2 | + |
| 3 | +class AnagramStrings { |
| 4 | + // method to check if two strings are anagrams |
| 5 | + public static boolean areAnagrams(String s1, String s2) { |
| 6 | + // Check if lengths are equal |
| 7 | + if (s1.length() != s2.length()) { |
| 8 | + return false; |
| 9 | + } |
| 10 | + |
| 11 | + // Create frequency arrays for both texts (ASCII size: 256) |
| 12 | + int[] frequency1 = new int[256]; |
| 13 | + int[] frequency2 = new int[256]; |
| 14 | + |
| 15 | + // Count frequency of each character in both texts |
| 16 | + for (int i = 0; i < s1.length(); i++) { |
| 17 | + frequency1[s1.charAt(i)]++; |
| 18 | + frequency2[s2.charAt(i)]++; |
| 19 | + } |
| 20 | + |
| 21 | + // Compare the frequency arrays |
| 22 | + for (int i = 0; i < 256; i++) { |
| 23 | + if (frequency1[i] != frequency2[i]) { |
| 24 | + return false; |
| 25 | + } |
| 26 | + } |
| 27 | + return true; |
| 28 | + } |
| 29 | + |
| 30 | + // Main method |
| 31 | + public static void main(String[] args) { |
| 32 | + Scanner input = new Scanner(System.in); |
| 33 | + |
| 34 | + System.out.print("Enter first text: "); |
| 35 | + String text1 = input.nextLine(); |
| 36 | + |
| 37 | + System.out.print("Enter second text: "); |
| 38 | + String text2 = input.nextLine(); |
| 39 | + |
| 40 | + // Convert both strings to lowercase and remove spaces |
| 41 | + text1 = text1.toLowerCase().replaceAll("\\s", ""); |
| 42 | + text2 = text2.toLowerCase().replaceAll("\\s", ""); |
| 43 | + |
| 44 | + // Check if the texts are anagrams |
| 45 | + if (areAnagrams(text1, text2)) { |
| 46 | + System.out.println("The texts are anagrams"); |
| 47 | + } else { |
| 48 | + System.out.println("The texts are not anagrams"); |
| 49 | + } |
| 50 | + } |
| 51 | +} |
0 commit comments