Easy Understanding Java Code With Explaination


  • 0
    N
    Use a HashMap and a HashSet. A word is unique when satisfies these 2 conditions
    
     1. Abbreviation of the given word doesn't exist in the abbr_List of the dictionary
     2. Abbreviation of the given word exist in the abbr_List, however, only this word in the dict has the abbr, so the size of the hashset should be 1.
    
    
    HashMap<String,HashSet<String>> map = new HashMap<String,HashSet<String>>();
    public ValidWordAbbr(String[] dict) {
        for(String word:dict){
            String abbr = calAbbr(word);
            if(map.containsKey(abbr)){
                map.get(abbr).add(word);
            }else{
                HashSet<String> set = new HashSet<String>();
                set.add(word);
                map.put(abbr,set);
            }
        }
    }
    
    public String calAbbr(String word){
        if(word.length()<=2) return word;
        int len = word.length()-2;
        String abbr = ""+word.charAt(0)+len+word.charAt(word.length()-1);
        return abbr;
    }
    
    public boolean isUnique(String word) {
        String abbr = calAbbr(word);
        if(!map.containsKey(abbr)) return true;
        if(map.get(abbr).contains(word) && map.get(abbr).size()==1) return true;
        return false;
    }

Log in to reply
 

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