JavaAlgorithms/Strings/CheckAnagrams.java

53 lines
1.3 KiB
Java
Raw Normal View History

2021-09-26 15:57:21 +08:00
package Strings;
import java.util.HashMap;
import java.util.Map;
/**
2020-10-24 18:23:28 +08:00
* Two strings are anagrams if they are made of the same letters arranged differently (ignoring the
* case).
*/
public class CheckAnagrams {
2021-02-21 09:02:32 +08:00
public static void main(String[] args) {
assert isAnagrams("Silent", "Listen");
assert isAnagrams("This is a string", "Is this a string");
assert !isAnagrams("There", "Their");
}
2021-02-21 09:02:32 +08:00
/**
* Check if two strings are anagrams or not
*
* @param s1 the first string
* @param s2 the second string
* @return {@code true} if two string are anagrams, otherwise {@code false}
*/
public static boolean isAnagrams(String s1, String s2) {
int l1 = s1.length();
int l2 = s2.length();
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
Map<Character, Integer> charAppearances = new HashMap<>();
2021-02-21 09:02:32 +08:00
for (int i = 0; i < l1; i++) {
char c = s1.charAt(i);
int numOfAppearances = charAppearances.getOrDefault(c, 0);
charAppearances.put(c, numOfAppearances + 1);
}
2021-02-21 09:02:32 +08:00
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);
}
2021-02-21 09:02:32 +08:00
for (int cnt : charAppearances.values()) {
if (cnt != 0) {
return false;
}
}
2021-02-21 09:02:32 +08:00
return true;
}
}