Guest User

Untitled

a guest
Aug 9th, 2016
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.89 KB | None | 0 0
  1. boolean anagram(String a, String b) {
  2.     Map<String, Integer> occA = countOccurences(a);
  3.     Map<String, Integer> occB = countOccurences(b);
  4.     Set<String> uniqueCharacters = getUniqueCharacters(a, b);
  5.     for (String ch : uniqueCharacters) {
  6.         if (occA.getOrDefault(ch, 0) != occB.getOrDefault(ch, 0)) {
  7.             return false;
  8.         }
  9.     }
  10.     return true;
  11. }
  12.  
  13. private Set<String> getUniqueCharacters(String a, String b) {
  14.     Set<String> uniqueCharacters = new HashSet<>();
  15.     for (int i = 0; i < a.length; i++) {
  16.         uniqueCharacters.add(a[i]);
  17.     }
  18.     for (int j = 0; j < b.length; j++) {
  19.         uniqueCharacters.add(b[j]);
  20.     }
  21.     return uniqueCharacters;
  22. }
  23.  
  24. private Map<String, Integer> countOccurences(String str) {
  25.     Map<String, Integer> occurences = new HashMap<>();
  26.     for (int i = 0; i < str.length; i++) {
  27.         occurences.putIfAbsent(str[i], 0);
  28.         occurences.put(str[i], occurences.get(str[i]) + 1);
  29.     }
  30.     return occurences;
  31. }
Advertisement
Add Comment
Please, Sign In to add comment