Skip to content

Commit a475463

Browse files
reducing complexity to linear complixity (TheAlgorithms#2087)
* reducing complexity to linear complixity * reducing complexity to linear * update CheckAnagrams algo Co-authored-by: Yang Libin <contact@yanglibin.info>
1 parent 93d1a5c commit a475463

File tree

1 file changed

+42
-22
lines changed

1 file changed

+42
-22
lines changed

strings/CheckAnagrams.java

Lines changed: 42 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,52 @@
11
package strings;
22

3-
import java.util.Arrays;
3+
import java.util.HashMap;
4+
import java.util.Map;
45

56
/**
67
* Two strings are anagrams if they are made of the same letters arranged differently (ignoring the
78
* case).
89
*/
910
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+
}
1516

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+
}
3252
}

0 commit comments

Comments
 (0)