My java solution using hashmap


  • 1
    A
    public List<List<String>> groupAnagrams(String[] s) {
        List<List<String>> ans = new LinkedList<>();
        HashMap<String, Integer> hash = new HashMap<>();
        Arrays.sort(s);
        int n = s.length;
        char[] buf;
        String dum;
        int j;
        for (int i = 0; i < n; i++) {
            buf = s[i].toCharArray();
            Arrays.sort(buf);
            dum = new String(buf);
            if (hash.containsKey(dum)) {
                ans.get(hash.get(dum)).add(s[i]);
            } else {
                ans.add(new LinkedList<String>());
                ans.get(ans.size() - 1).add(s[i]);
                hash.put(dum, ans.size() - 1);
            }
        }
        return ans;
    }

Log in to reply
 

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