Why this is a wrong answer?


  • 0
    N

    Input: ["tea","and","ate","eat","den"]

    Output: [["tea","ate","eat"],["and"],["den"]]

    Expected: [["den"],["and"],["ate","eat","tea"]]

    my code:

    public class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            List<List<String>> res = new ArrayList<>();
            HashMap<String, ArrayList<String>> hm = new HashMap<>();
            
            if(strs == null || strs.length == 0){
                return res;
            }
            
            for(int i = 0; i < strs.length; i++){
                String sortedStr = sortStr(strs[i]);
                ArrayList<String> list = hm.get(sortedStr);
                if(list != null){
                    list.add(strs[i]);
                }
                else{
                    list = new ArrayList<>();
                    list.add(strs[i]);
                    hm.put(sortedStr, list);
                }
            }
            
            for(Map.Entry<String, ArrayList<String>> entry : hm.entrySet()){
                res.add(hm.get(entry.getKey()));
            }
            
            return res;
        }
        
        public String sortStr(String str){
            char[] charAry = str.toCharArray();
            Arrays.sort(charAry);
            return new String(charAry);
        }
    }

  • 0
    R

    For the return value, each inner list's elements must follow the lexicographic order.


  • 0
    L

    You should sort the List<Integer>: ["tea","ate","eat"] ->["ate","eat","tea"]


Log in to reply
 

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