Java 43ms 94.44% solution


  • 0
    M
    public class ValidWordAbbr {
        private Map<String, String> map = new HashMap<>();
    
        public ValidWordAbbr(String[] dict) {
            for (String s : dict) {
                String key = getKey(s);
                if (key != null) {
                    if (map.containsKey(key)) {
                        map.put(key, "#");
                    }
                    else {
                        map.put(key, s);
                    }
                }
            }
        }
    
        public boolean isUnique(String s) {
            String key = getKey(s);
            return !map.containsKey(key) || map.get(key).equals(s);
        }
        
        private String getKey(String s) {
            int len = s.length();
            if (len >= 3) {
                return s.charAt(0) + String.valueOf(len) + s.charAt(len - 1);
            }
            else {
                return null;
            }
        }
    }
    

    It requires that one abbreviation can only come from one word. So, no need for set.


  • 0
    H

    Your solution is wrong.
    Try ["dog", "dog"] with "dog". The solution should be true
    (same as ["a", "a"] with "a", OJ returns true)


  • 0
    M

    ["a", "a"] with "a" returns true because a doesn't have abbr. The uniqueness is based on abbr.s. On the other hand, the abbr. for "dog" is already in the dict.


Log in to reply
 

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