|
8 | 8 | * case). |
9 | 9 | */ |
10 | 10 | public class CheckAnagrams { |
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 | | - } |
| 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 | + } |
16 | 16 |
|
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<>(); |
| 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 | 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 | | - } |
| 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 | 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 | | - } |
| 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 | 44 |
|
45 | | - for (int cnt : charAppearances.values()) { |
46 | | - if (cnt != 0) { |
47 | | - return false; |
48 | | - } |
49 | | - } |
50 | | - return true; |
| 45 | + for (int cnt : charAppearances.values()) { |
| 46 | + if (cnt != 0) { |
| 47 | + return false; |
| 48 | + } |
51 | 49 | } |
| 50 | + return true; |
| 51 | + } |
52 | 52 | } |
0 commit comments