Why not list of list of strings as output?


  • 31
    M

    Why the output is list and not a list of list. What If there are multiple groups of anagrams?


  • 0
    G

    I have the same question. Why not List<List<String>>??


  • -2
    W

    The problem asks us to return all groups of strings that are anagrams. So all we need to do is to group them and add them into one list.


  • -2
    D

    My easy to understand solution!

    public List<String> anagrams(String[] strs) {
        List<String> res = new LinkedList<String>();
        if(strs==null || strs.length==0) {
            return res;
        }
        Map<String, String> map = new HashMap<String, String>();
        for(String elem: strs){
            char[] array = elem.toCharArray();
            Arrays.sort(array);
            String sorted_str = new String(array);
            if(map.containsKey(sorted_str)) {
                String temp = map.get(sorted_str);
                if(temp.length()==0 || temp.charAt(0) != '+') {
                    res.add(temp);
                    temp = "+"+temp;
                    map.put(sorted_str, temp);
                }
                res.add(elem);
            }else {
                map.put(sorted_str, elem);
            }
        }
        return res;
    }

  • 0

    Hi, mahdy. For your question, here has a very nice discussion. Yeah, the problem description is not that clear.


  • 0
    G

    I think that the result is a List about the strings given, not the list of the list of all kinds of anagrams.


  • 1

    Please see this post. I have updated the problem description and provided a clear example. I have also changed the return type to return list<list<strings>>.


Log in to reply
 

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