Java Anagrams Solution with explanation.

  • 0

    The idea is that, we sort each strings, and then compare if they are equal. Use HashMap<String,
    List<String>> map to record the sorted string and its corresponding list: if the sorted string has already exist in the map, just add this string into the list; if the sorted string is not exist in the map, create a new list to hold this string and add this relationship into hashmap.

    public class Solution {

    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> ret = new ArrayList<List<String>>();
        if(strs == null || strs.length == 0){
            return ret;
        HashMap<String, List<String>> map = new HashMap<String, List<String>>();
        for(int i = 0; i < strs.length; i++){
            char[] chars = strs[i].toCharArray();
            String s = new String(chars);
                List<String> list = new ArrayList<String>();
                map.put(s, list);
                List<String> ls = map.get(s);
        return ret;


Log in to reply

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