Skip to content

Instantly share code, notes, and snippets.

@nashid
Created November 6, 2016 17:27
Show Gist options
  • Save nashid/76788c15ada6b3b91d8f3e8bf3730167 to your computer and use it in GitHub Desktop.
Save nashid/76788c15ada6b3b91d8f3e8bf3730167 to your computer and use it in GitHub Desktop.
package kata.string;
import java.util.Map;
import java.util.HashMap;
public class Anagram {
private static Map<Character, Integer> toMap(String str) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
Character character = str.charAt(i);
if (map.containsKey(character)) {
Integer count = map.get(character);
map.put(character, count++);
}
else {
map.put(character, 1);
}
}
return map;
}
public static boolean isAnagram(String str1, String str2) {
if (str1 == null || str2 == null) { return false; }
boolean result = false;
Map<Character, Integer> map1 = toMap(str1);
Map<Character, Integer> map2 = toMap(str2);
for (Map.Entry<Character, Integer> entry : map1.entrySet()) {
Integer count1 = entry.getValue();
Integer count2 = map2.get(entry.getKey());
if (count2 == null || count1 != count2) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment