Java Solution using HashMap


  • 0
    M

    The problem is not well described though.

    public class ValidWordAbbr {
        Map<String, Set<String>> map = new HashMap<>();
        public ValidWordAbbr(String[] dictionary) {
            for (String s : dictionary) {
                String abbr = abbr(s);
                if (!map.containsKey(abbr)) map.put(abbr, new HashSet<String>());
                map.get(abbr).add(s);
            }
        }
        
        public boolean isUnique(String word) {
            String abbr = abbr(word);
            if (!map.containsKey(abbr)) return true;
            return map.get(abbr).contains(word) && map.get(abbr).size() == 1;
        }
        private String abbr(String s) {
            if (s == null || s.length() <= 2) return s;
            return s.substring(0, 1) + (s.length() - 2) + s.substring(s.length() - 1);
        }
    }
    

Log in to reply
 

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