26ms Java Solution with O(n) complexity


  • 0
    G
    public class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            Map<String, List<String>> map = new HashMap<String, List<String>>();
            String[] orderStrs = order(strs);
            for(int i = 0;i < orderStrs.length;i++) {
                if(!map.containsKey(orderStrs[i])) map.put(orderStrs[i], new ArrayList<String>());
                map.get(orderStrs[i]).add(strs[i]);
            }
            return new ArrayList<List<String>>(map.values());
        }
        
        public String[] order(String[] strs) {
            String[] res = new String[strs.length];
            for(int i = 0;i < strs.length;i++) {
                char[] c = strs[i].toCharArray();
                Arrays.sort(c);
                res[i] = String.valueOf(c);
            }
            return res;
        }
    }
    

Log in to reply
 

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