Cleaner implementation of Categorize by Count solution in Java (no # as delimiter)


  • 0
    R

    The Categorize by Count solution given by leetcode uses # to separate the counts and create a string out of it. So that it can be used as hash key. It is possible to use the array itself as the hash key but given our own implementation of equals and hashCode which considers the elements of the array.

    class Solution {
      public List<List<String>> groupAnagrams(String[] strs) {
        Map<CharacterCounts, List<String>> groupedAnagrams = new HashMap<>();
    
        for (String str : strs) {
          List<String> anagrams = new LinkedList<>();
          CharacterCounts key = new CharacterCounts(str);
          if (groupedAnagrams.containsKey(key)) {
            anagrams = groupedAnagrams.get(key);
          }
          anagrams.add(str);
          groupedAnagrams.put(key, anagrams);
        }
        return new LinkedList<>(groupedAnagrams.values());
      }
    
      private class CharacterCounts {
        // given all inputs will be lowercase alphabets
        private int[] counts = new int[26];
    
        CharacterCounts(String str) {
          Arrays.fill(this.counts, 0);
          if (str != null) {
            for (int i = 0; i < str.length(); i++) {
              counts[str.charAt(i) - 'a'] += 1;
            }
          }
        }
    
        @Override
        public boolean equals(Object o) {
          if (this == o) return true;
          if (o == null || getClass() != o.getClass()) return false;
          CharacterCounts that = (CharacterCounts) o;
          return Arrays.equals(counts, that.counts);
        }
    
        @Override
        public int hashCode() {
          return Arrays.hashCode(counts);
        }
      }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.