Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- boolean anagram(String a, String b) {
- Map<String, Integer> occA = countOccurences(a);
- Map<String, Integer> occB = countOccurences(b);
- Set<String> uniqueCharacters = getUniqueCharacters(a, b);
- for (String ch : uniqueCharacters) {
- if (occA.getOrDefault(ch, 0) != occB.getOrDefault(ch, 0)) {
- return false;
- }
- }
- return true;
- }
- private Set<String> getUniqueCharacters(String a, String b) {
- Set<String> uniqueCharacters = new HashSet<>();
- for (int i = 0; i < a.length; i++) {
- uniqueCharacters.add(a[i]);
- }
- for (int j = 0; j < b.length; j++) {
- uniqueCharacters.add(b[j]);
- }
- return uniqueCharacters;
- }
- private Map<String, Integer> countOccurences(String str) {
- Map<String, Integer> occurences = new HashMap<>();
- for (int i = 0; i < str.length; i++) {
- occurences.putIfAbsent(str[i], 0);
- occurences.put(str[i], occurences.get(str[i]) + 1);
- }
- return occurences;
- }
Advertisement
Add Comment
Please, Sign In to add comment