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


  • 0
    N

    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());
                map.get(abbr).add(s);
            }
        }
    
        public boolean isUnique(String word) {
            if(map.size() == 0) return true;
            String abbr = helper(word);
            if(map.containsKey(abbr)){
                if(map.get(abbr).contains(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.charAt(0));
                sb.append(s.length() - 2);
                sb.append(s.charAt(s.length() - 1));
                return sb.toString();
            }
            return s;
        }
    }

  • 0
    S

    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.