reducing complexity to linear complixity (#2087)

* reducing complexity to linear complixity

* reducing complexity to linear

* update CheckAnagrams algo

Co-authored-by: Yang Libin <contact@yanglibin.info>
This commit is contained in:
ITAY VENTURA
2021-02-21 03:02:07 +02:00
committed by GitHub
parent 93d1a5c12b
commit a475463146

View File

@ -1,32 +1,52 @@
package strings; package strings;
import java.util.Arrays; import java.util.HashMap;
import java.util.Map;
/** /**
* Two strings are anagrams if they are made of the same letters arranged differently (ignoring the * Two strings are anagrams if they are made of the same letters arranged differently (ignoring the
* case). * case).
*/ */
public class CheckAnagrams { public class CheckAnagrams {
public static void main(String[] args) { public static void main(String[] args) {
assert isAnagrams("Silent", "Listen"); assert isAnagrams("Silent", "Listen");
assert isAnagrams("This is a string", "Is this a string"); assert isAnagrams("This is a string", "Is this a string");
assert !isAnagrams("There", "Their"); assert !isAnagrams("There", "Their");
} }
/** /**
* Check if two strings are anagrams or not * Check if two strings are anagrams or not
* *
* @param s1 the first string * @param s1 the first string
* @param s2 the second string * @param s2 the second string
* @return {@code true} if two string are anagrams, otherwise {@code false} * @return {@code true} if two string are anagrams, otherwise {@code false}
*/ */
public static boolean isAnagrams(String s1, String s2) { public static boolean isAnagrams(String s1, String s2) {
s1 = s1.toLowerCase(); int l1 = s1.length();
s2 = s2.toLowerCase(); int l2 = s2.length();
char[] values1 = s1.toCharArray(); s1 = s1.toLowerCase();
char[] values2 = s2.toCharArray(); s2 = s2.toLowerCase();
Arrays.sort(values1); Map<Character, Integer> charAppearances = new HashMap<>();
Arrays.sort(values2);
return new String(values1).equals(new String(values2)); for (int i = 0; i < l1; i++) {
} char c = s1.charAt(i);
int numOfAppearances = charAppearances.getOrDefault(c, 0);
charAppearances.put(c, numOfAppearances + 1);
}
for (int i = 0; i < l2; i++) {
char c = s2.charAt(i);
if (!charAppearances.containsKey(c)) {
return false;
}
charAppearances.put(c, charAppearances.get(c) - 1);
}
for (int cnt : charAppearances.values()) {
if (cnt != 0) {
return false;
}
}
return true;
}
} }