Advertisement
exmkg

Untitled

Aug 23rd, 2024
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. class Solution {
  2.     public List<List<String>> groupAnagrams(String[] strs) {
  3.         Map<String, List<String>> map = new HashMap<>();
  4.  
  5.         // L = length of all strings together
  6.         // T: O(L log L)
  7.         // S: O(L)
  8.  
  9.         for (String word : strs) {  // O(N)
  10.             // Each anagram can be identified uniquely
  11.             // by a sorted list of its characters.
  12.             //
  13.             // For each word, create its copy
  14.             // with all characters sorted.
  15.             char[] chars = word.toCharArray();
  16.             Arrays.sort(chars);
  17.             String sortedWord = new String(chars);
  18.  
  19.             // if (map doesn't contain key sortedWord, i.e. such anagram was never seen before) {
  20.             //   create an empty list for that new anagram
  21.             // }  
  22.             // add to this list the current word as it corresponds to that anagram
  23.             if (!map.containsKey(sortedWord)) {
  24.                 map.put(sortedWord, new ArrayList<>());
  25.             }
  26.             map.get(sortedWord).add(word);
  27.         }
  28.        
  29.         return new ArrayList<>(map.values());
  30.     }
  31. }
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement