|
1 | 1 | package strings;
|
2 | 2 |
|
3 |
| -import java.util.Arrays; |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
4 | 5 |
|
5 | 6 | /**
|
6 | 7 | * Two strings are anagrams if they are made of the same letters arranged differently (ignoring the
|
7 | 8 | * case).
|
8 | 9 | */
|
9 | 10 | public class CheckAnagrams {
|
10 |
| - public static void main(String[] args) { |
11 |
| - assert isAnagrams("Silent", "Listen"); |
12 |
| - assert isAnagrams("This is a string", "Is this a string"); |
13 |
| - assert !isAnagrams("There", "Their"); |
14 |
| - } |
| 11 | + public static void main(String[] args) { |
| 12 | + assert isAnagrams("Silent", "Listen"); |
| 13 | + assert isAnagrams("This is a string", "Is this a string"); |
| 14 | + assert !isAnagrams("There", "Their"); |
| 15 | + } |
15 | 16 |
|
16 |
| - /** |
17 |
| - * Check if two strings are anagrams or not |
18 |
| - * |
19 |
| - * @param s1 the first string |
20 |
| - * @param s2 the second string |
21 |
| - * @return {@code true} if two string are anagrams, otherwise {@code false} |
22 |
| - */ |
23 |
| - public static boolean isAnagrams(String s1, String s2) { |
24 |
| - s1 = s1.toLowerCase(); |
25 |
| - s2 = s2.toLowerCase(); |
26 |
| - char[] values1 = s1.toCharArray(); |
27 |
| - char[] values2 = s2.toCharArray(); |
28 |
| - Arrays.sort(values1); |
29 |
| - Arrays.sort(values2); |
30 |
| - return new String(values1).equals(new String(values2)); |
31 |
| - } |
| 17 | + /** |
| 18 | + * Check if two strings are anagrams or not |
| 19 | + * |
| 20 | + * @param s1 the first string |
| 21 | + * @param s2 the second string |
| 22 | + * @return {@code true} if two string are anagrams, otherwise {@code false} |
| 23 | + */ |
| 24 | + public static boolean isAnagrams(String s1, String s2) { |
| 25 | + int l1 = s1.length(); |
| 26 | + int l2 = s2.length(); |
| 27 | + s1 = s1.toLowerCase(); |
| 28 | + s2 = s2.toLowerCase(); |
| 29 | + Map<Character, Integer> charAppearances = new HashMap<>(); |
| 30 | + |
| 31 | + for (int i = 0; i < l1; i++) { |
| 32 | + char c = s1.charAt(i); |
| 33 | + int numOfAppearances = charAppearances.getOrDefault(c, 0); |
| 34 | + charAppearances.put(c, numOfAppearances + 1); |
| 35 | + } |
| 36 | + |
| 37 | + for (int i = 0; i < l2; i++) { |
| 38 | + char c = s2.charAt(i); |
| 39 | + if (!charAppearances.containsKey(c)) { |
| 40 | + return false; |
| 41 | + } |
| 42 | + charAppearances.put(c, charAppearances.get(c) - 1); |
| 43 | + } |
| 44 | + |
| 45 | + for (int cnt : charAppearances.values()) { |
| 46 | + if (cnt != 0) { |
| 47 | + return false; |
| 48 | + } |
| 49 | + } |
| 50 | + return true; |
| 51 | + } |
32 | 52 | }
|
0 commit comments