nklogk Java solution beats 97%


  • 0
    L

    Sorts n strings with length k and then iterates. The time complexity is nklogk.

    public List<List<String>> groupAnagrams(String[] strs) {
            if(strs.length==0) {
                return Collections.emptyList();
            }
            
            Map<String,List<String>> map = new HashMap<>();
            for(String s : strs) {
                char[] arr = s.toCharArray();
                Arrays.sort(arr);
                String temp = new String(arr);
                List<String> l = map.get(temp);
                if(l == null) {
                    l = new ArrayList<>();
                    map.put(temp,l);
                }
                l.add(s);             
                
            }
             List<List<String>> ret = new ArrayList<>(map.values());
             return ret;
        }
    

Log in to reply
 

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