Java solution for the updated version


  • 1
    X
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> rst = new ArrayList<List<String>>();
        if (strs == null || strs.length == 0) return rst;
        Map<String, Integer> map = new HashMap<String, Integer>();
        int count = 0;
        Arrays.sort(strs);
        for (int i=0; i<strs.length; i++) {
        	char[] ch = strs[i].toCharArray();
        	Arrays.sort(ch);
        	String temp = String.valueOf(ch);
        	if (map.containsKey(temp)) {
        		int index = map.get(temp);
        		rst.get(index).add(strs[i]);
        	} else {
        		map.put(temp, count++);
        		List<String> cur = new ArrayList<String>();
        		cur.add(strs[i]);
        		rst.add(cur);
        	}
        }
        return rst;
    }

Log in to reply
 

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