Unique Word Abbreviation


  • 0

    Click here to see the full article post


  • 1
    A

    We can do it by just storing 1 map and no set.

    Map<String,String> map;
        public ValidWordAbbr(String[] dictionary) {
            map = new HashMap<>();
            for(String word : dictionary){
                if(word == null) continue;
                if(word.length() <= 2) map.put(word,word);
                else {
                    String abr = word.charAt(0) + "" + (word.length()-2) + word.charAt(word.length()-1);
                    if(map.containsKey(abr) && !word.equals(map.get(abr))) map.put(abr,new String());
                    else map.put(abr,word);
                }
            }
            System.out.println(map);
        }
    
        public boolean isUnique(String word) {
            if(word == null) return false;
            if(word.length() <= 2) return true;
            String abr = word.charAt(0) + "" + (word.length()-2) + word.charAt(word.length()-1);
            return (!map.containsKey(abr) || (word.equals(map.get(abr))));
        }
    

  • 0
    S

    How does solution 3 handle duplicate entries in the dictionary?

    For example, ['a', 'a'] would produce the hash: 'a' : false
    isUnique(a) would then fail.


  • 0
    S

    Nevermind, I see that the array is converted into a set.


  • 0
    R

    You should specify that a "match" is counted as unique & not duplicate e.g. if the word is "dog" or "bat" and the list is ["dog", "cat", "fat"] you expect true for both dog & bat, even though there is a perfect match for dog & there is no match for bat. Yet both "dog" and "bat" are considered unique.


Log in to reply
 

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