Unique Word Abbreviation

An abbreviation of a word follows the form <first letter><number><last letter>. 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, Integer> map;
    Set<String> set;

    public ValidWordAbbr(String[] dictionary) {
        set = new HashSet<>();
        map = new HashMap<>();
        for (String s : dictionary) {
            if (s.length() <= 1) return;
            String key = convert(s);
            map.merge(key, 1, (a, b) -> a + b);
            set.add(s);
        }
    }

    public boolean isUnique(String word) {
        if (word == null || word.length() <= 1) return true;
        String key = convert(word);
        if (map.containsKey(key)) {
            if (map.get(key) >= 2) {
                return false;
            } else if (set.contains(word)){
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    private String convert(String s) {
        if (s.length() <= 1) return "";

        StringBuffer key = new StringBuffer();
        key.append(s.charAt(0));
        key.append(s.charAt(s.length() - 1));
        key.append(s.length() - 2);
        return key.toString();
    }
}


// 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 ""