My 27ms java short and easy understand solution


  • 2
    S
    public List<List<String>> groupAnagrams(String[] strs) {
            List<List<String>> res = new ArrayList<List<String>>();
    	Map<String, Integer> map = new HashMap<String, Integer>();
    	for (String string : strs) {
    		char[] cs = string.toCharArray();
    		Arrays.sort(cs);
    		String sortedStr = String.valueOf(cs);
    		if (map.containsKey(sortedStr)){
    			res.get(map.get(sortedStr)).add(string);
    		}else{
    			map.put(sortedStr, map.size());
    			List<String> list = new ArrayList<String>();
    			list.add(string);
    			res.add(list);
    		}
    	}
    	return res;
    }
    

  • 0
    G

    @shawloatrchen the only difference between your solution and one of the top solutions is that you did not do the sorting for the strings, that is the lists in your res list is not in lexical order.


  • 0
    G

    @guolei329 also you used Integer as values, which corresponding to the index of the lists in res. The same idea from the beat 100% Java solution. Good combination though!


  • 0
    S

    @guolei329 I haven't see the very top one solution when I write my code, and my code is faster than it, thanks for your comment.


  • 0
    G

    @shawloatrchen Oh, dude, don't misunderstand what I said in my last post. I just said your idea is very similar to what in those top solutions not that you referred to them. Still thumb up for your brilliant idea.


  • 0
    S

    @guolei329 haha, thanks


Log in to reply
 

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