Skip to content

Instantly share code, notes, and snippets.

@Semigradsky
Last active July 5, 2019 09:09
Show Gist options
  • Save Semigradsky/5d787f7cf4cadb456e2333e9e55ef541 to your computer and use it in GitHub Desktop.
Save Semigradsky/5d787f7cf4cadb456e2333e9e55ef541 to your computer and use it in GitHub Desktop.
private static Collection collectAnagrams(String[] dictionary, String searchAnagramsFor) {
HashMap<Character, Integer> hashMap = new HashMap<>();
for (int i = 0; i < searchAnagramsFor.length(); i++) {
char c = Character.toLowerCase(searchAnagramsFor.charAt(i));
if (!hashMap.containsKey(c)) {
hashMap.put(c, 0);
}
hashMap.put(c, hashMap.get(c) + 1);
}
List<String> list = new ArrayList<>();
for (String el : dictionary) {
if (el.length() == searchAnagramsFor.length() && isAnagram(el, (HashMap<Character, Integer>) hashMap.clone())) {
list.add(el);
}
}
return list;
}
private static boolean isAnagram(String s1, HashMap<Character, Integer> hashMap) {
for (int i = 0; i < s1.length(); i++) {
char c = Character.toLowerCase(s1.charAt(i));
if (!hashMap.containsKey(c) || hashMap.get(c) == 0) {
return false;
}
hashMap.put(c, hashMap.get(c) - 1);
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment