An abbreviation of a word follows the form . Below are some examples of word abbreviations:

a) it                      --> it    (no abbreviation)

     1
b) d|o|g                   --> d1g

              1    1  1
     1---5----0----5--8
c) i|nternationalizatio|n  --> i18n

              1
     1---5----0
d) l|ocalizatio|n          --> l10n

Assume you have a dictionary and given a word, find whether its abbreviation is unique in the dictionary. A word's abbreviation is unique if no other word from the dictionary has the same abbreviation.

Example:

Given dictionary = [ "deer", "door", "cake", "card" ]

isUnique("dear") -> 
false

isUnique("cart") -> 
true

isUnique("cane") -> 
false

isUnique("make") -> 
true

Solution

public class ValidWordAbbr {
    Map<String, Map<Integer, Integer>> map = new HashMap<String, Map<Integer, Integer>>();
    Map<String, Integer> occur = new HashMap<String, Integer>();
    public ValidWordAbbr(String[] dictionary) {
        for(String s: dictionary) {
            StringBuilder sb = new StringBuilder();
            if(s.length() <= 1) sb.append(s);
            else {sb.append(s.charAt(0)); sb.append(s.charAt(s.length()-1));}

            String key = sb.toString();
            if(!map.containsKey(key)) map.put(key, new HashMap<Integer, Integer>());
            if(!map.get(key).containsKey(s.length())) map.get(key).put(s.length(), 0);
            map.get(key).put(s.length(), map.get(key).get(s.length()) + 1);

            occur.put(s, occur.getOrDefault(s, 0) + 1);
        }
    }

    public boolean isUnique(String word) {
        StringBuilder sb = new StringBuilder();
        if(word.length() <= 1) sb.append(word);
        else {sb.append(word.charAt(0)); sb.append(word.charAt(word.length()-1));}
        String key = sb.toString();
        if(!map.containsKey(key)) return true;
        if(!map.get(key).containsKey(word.length())) return true;
        return occur.containsKey(word) && map.get(key).get(word.length()) == occur.get(word);
    }
}


// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
// vwa.isUnique("Word");
// vwa.isUnique("anotherWord");

results matching ""

    No results matching ""