My Java solution using HashMap


  • 4
    N

    Running time is about 600 ms. Please advise if there is any way to optimize.

    Thanks!

    public class Solution {
        public static List<String> anagrams(String[] strs) {
        	
        	HashMap<String, List<String>> hashMap= new HashMap<String, List<String>>();
        	List<String> anagramStrings = new ArrayList<String>();
        	
        	for (String str: strs) {
        		char[] charArray = new char[str.length()];
        		charArray = str.replaceAll("\\s+", "").toCharArray();
        		Arrays.sort(charArray);
        		
        		String mapKey = String.copyValueOf(charArray);
        		
        		if (hashMap.containsKey(mapKey)) {
        			hashMap.get(mapKey).add(str);
        		} else {
        			List<String> stringList = new ArrayList<String>();
        			stringList.add(str);
        			hashMap.put(mapKey, stringList);
        		}
        	}
        	
        	for(Map.Entry<String, List<String>> entry: hashMap.entrySet()) {
        		List<String> value = entry.getValue();
        		
        		if (value.size() > 1) {
        			anagramStrings.addAll(value);
        		}	
        	}
        	return anagramStrings;
    
        }
    
    }

  • 0
    A

    In my solution (586ms) instead of keeping a separate lists in the hash map, I kept the fist string with the given hash code and put the strings directly to the output list:

    String ph = new String("place_holder");
    ...
        String sp = map.get(key);
        if( sp != null ) {
            if( sp != ph ) {
                list.add(sp);
                map.put(key,ph);
            }
            list.add(s);
        } else {
            map.put(key,s);
        }

Log in to reply
 

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