288. Unique Word Abbreviation

Problem:
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
Analysis:
The abbreviation has just one form, starting char + number of chars between + ending char. The basic idea is to use a map to store the abbr and its word. There are several situations need to be considered.
1. word's abbr not in map
   return true
2. word's abbr in map but the value equals to word.
   return false
3. more than 1 words in dictionary share same abbr, set value to any non character char.

Solution:

 class ValidWordAbbr {
    Map<String, String> map = new HashMap<>();
    public ValidWordAbbr(String[] dictionary) {
        for (String str: dictionary) {
            String key = getKey(str);
            if (map.containsKey(key) && !map.get(key).equals(str)) {
                map.put(key, "");   
            }
            if (!map.containsKey(key)) {
                map.put(key, str);
            }
        }
    }
    
    public boolean isUnique(String word) {
        String key = getKey(word);
        return !map.containsKey(key) || map.get(key).equals(word);
    }

    private String getKey(String str) {
        if (str.length() < 3) return str;
        StringBuilder sb = new StringBuilder();
        sb.append(str.charAt(0)).append(Integer.toString(str.length() - 2)).append(str.charAt(str.length() - 1));
        return sb.toString();
    }
}


/**
 * Your ValidWordAbbr object will be instantiated and called as such:
 * ValidWordAbbr obj = new ValidWordAbbr(dictionary);
 * boolean param_1 = obj.isUnique(word);
 */

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List