Java AC solution share using HashMap<String, List<String>>

  • 0

    I clicked "submit solution" button 10 times before my code got accepted.

    It is VERY IMPORTANT to read the question description carefully!

    public class ValidWordAbbr {
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        public ValidWordAbbr(String[] dictionary) {
            for(String s : dictionary){
                String abbr = helper(s);
                if(!map.containsKey(abbr)) map.put(abbr, new LinkedList());
        public boolean isUnique(String word) {
            if(map.size() == 0) return true;
            String abbr = helper(word);
                    return map.get(abbr).size() == 1;
                }else return false;
            }else return true;
        private String helper(String s){
            if(s.length() > 2){
                StringBuilder sb = new StringBuilder();
                sb.append(s.length() - 2);
                sb.append(s.charAt(s.length() - 1));
                return sb.toString();
            return s;

  • 0

    I do not think using list here is a good idea here as the contains method will take linear time to find the target value. it is better to use a hashset.

Log in to reply

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