-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAnagramCheck.java
More file actions
37 lines (29 loc) · 1.04 KB
/
AnagramCheck.java
File metadata and controls
37 lines (29 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.Arrays;
public class AnagramCheck {
public static boolean isAnagram(String str1, String str2) {
// Remove spaces and convert to lowercase for normalization
str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();
// If lengths differ, they can't be anagrams
if (str1.length() != str2.length()) {
return false;
}
// Convert to char arrays
char[] arr1 = str1.toCharArray();
char[] arr2 = str2.toCharArray();
// Sort both arrays
Arrays.sort(arr1);
Arrays.sort(arr2);
// Compare sorted arrays
return Arrays.equals(arr1, arr2);
}
public static void main(String[] args) {
String word1 = "listen";
String word2 = "silent";
if (isAnagram(word1, word2)) {
System.out.println(word1 + " and " + word2 + " are anagrams.");
} else {
System.out.println(word1 + " and " + word2 + " are NOT anagrams.");
}
}
}