Java Solution - User Index instead of Partial result in HashMap


  • 0
    public class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            if (strs.length == 0) return Collections.emptyList(); 
            
            List<List<String>> res = new LinkedList<>(); 
            HashMap<String, Integer> map = new HashMap<>(); 
    
            int cnt = 0; 
            int index = 0; 
            
            for (String s : strs) {
                char[] chars = s.toCharArray(); 
                Arrays.sort(chars);
                String key = Arrays.toString(chars); 
                
                if (!map.containsKey(key)) {
                    // index of this group of Anagrams in the result
                    map.put(key, cnt); 
                    cnt++; 
     
                    List<String> curr = new LinkedList<String>(); 
                    curr.add(s); 
                    res.add(curr); 
                } else {
                    // retrieve the group list from the result
                    index = map.get(key); 
                    res.get(index).add(s); 
                }
            }
            
            return res; 
        }
    }

Log in to reply
 

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