-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagrams2.java
More file actions
40 lines (29 loc) · 960 Bytes
/
Anagrams2.java
File metadata and controls
40 lines (29 loc) · 960 Bytes
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
38
39
40
public class Anagrams2 {
public static boolean isAnagram(String str1, String str2) {
str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();
if (str1.length() != str2.length()) {
return false;
}
int[] count = new int[26];
for (int i = 0; i < str1.length(); i++) {
count[str1.charAt(i) - 'a']++;
}
for (int i = 0; i < str2.length(); i++) {
count[str2.charAt(i) - 'a']--;
}
for (int i : count) {
if (i != 0) return false;
}
return true;
}
public static void main(String[] args) {
String s1 = "Triangle";
String s2 = "Integral";
if (isAnagram(s1, s2)) {
System.out.println("The strings are anagrams.");
} else {
System.out.println("The strings are NOT anagrams.");
}
}
}