What's the problem in my code ?


  • 0
    R
    public List<List<String>> groupAnagrams(String[] strs) {
        Arrays.sort(strs);
        List<List<String>> rs = new ArrayList<List<String>>();
        Map<List<Character>, List<String>> test = new HashMap<List<Character>, List<String>>();
        for(int i = 0; i < strs.length; i ++){
            List<Character> tmp = new ArrayList<Character>();
            for(int j = 0; j < strs[i].length(); j ++)
                tmp.add(strs[i].charAt(j));
            Collections.sort(tmp);
            if(test.containsKey(tmp))
               test.get(tmp).add(strs[i]);
            else test.put(tmp, new ArrayList(Arrays.asList(strs[i])));
        }
        for(Map.Entry<List<Character>, List<String>> entry : test.entrySet())
            rs.add(entry.getValue());
        return rs;
    }
    

    when I add "Arrays.sort(strs)" at the beginning, it's Accepted。But when I delete the "Arrays.sort(strs)", I got Wrong Answer, why?


  • 0
    R

    One of the requirements is "For the return value, each inner list's elements must follow the lexicographic order."

    Without the sort the inner lists are in undetermined order. Another way to sort would be to change the last loop:

    for(Map.Entry<List<Character>, List<String>> entry : test.entrySet()) {
        Collections.sort(entry.getValue());        
        rs.add(entry.getValue());
    }

  • 0
    R

    3Q, I've ignored that....


Log in to reply
 

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