HashMap problem using Java


  • 0
    C

    Some of the results are not passed. I get the following error message:

    Input:
    ["tea","and","ate","eat","den"]
    Output:
    [["tea","ate","eat"],["and"],["den"]]
    Expected:
    [["den"],["and"],["ate","eat","tea"]]
    
    =============================================================================
     public static List<List<String>> anagrams(String[] strs) {
        
                List<List<String>> result = new ArrayList<List<String>>(); 
                HashMap< String, List<String>> hash =  new HashMap< String, List<String>>(); 
                
                if ( strs.length == 0 ) return null;  
        
        
            for ( String s : strs ){
    
                char[] ch = s.toCharArray();
                Arrays.sort(ch);
                String s1 = String.valueOf(ch);
    
                if ( hash.containsKey(s1) ){
    
                    hash.get(s1).add(s);                
                }
    
                else {
    
                    List<String> le = new ArrayList<String>(); 
                    le.add(s);
                    hash.put(s1, le);
                }      
            }
    
            for ( Map.Entry < String, List<String>> entry: hash.entrySet() ){
     
                for ( Map.Entry < String, List<String>> entry: hash.entrySet() ){
             
                      Collections.sort( entry.getValue() );
                      result.add( entry.getValue() );
        }
                result.add(entry.getValue() );
            }
            return result; 
        }

  • 2
    J

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

    ["tea","ate","eat"] Wrong, because the word "ate" starts with an "a", it should be place in front of "eat" and "tea", just like in the dictionary.

    ["ate","eat","tea"] Correct, because :ate"<"eat"<"tea".


  • 0
    C

    Thanks, I just add a line in the end for loop and the answer is correct now.

    for ( Map.Entry < String, List<String>> entry: hash.entrySet() ){
             
            // sort the ArrayList lexicographically 
            Collections.sort( entry.getValue() );
            result.add( entry.getValue() );
        }

Log in to reply
 

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