Java solution using HashMap + Set


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

Log in to reply
 

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