leetcode288 - Unique Word Abbreviation - medium

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)
b) d|o|g --> d1g
c) i|nternationalizatio|n --> i18n
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函數

 

理解題意:本題有陷阱。它對unique的定義是no other word from the dictionary has the same abbreviation. 這個other說的很巧妙,真實unique不僅僅指新來word的abbr之前徹底沒出現過的case,還指abbr之前出現過,但形成之前abbr的單詞和你今天剛傳入的單詞是同樣的。這樣的確仍是no other word給出同一個abbr。
舉例:
[cake cake jasmine]. << jack. j2k沒出現過,ok
[cake cake jasmine]. << cake. c2e出現過,但也是cake形成的,ok
[cake cane jasmine]. << cake. c2e出現過,並且有一個c2e是由other words(cane)產生的,no.spa

最後問題等價轉化:若是用兩個map,存儲對原始字符串的頻率統計,以及縮寫字符串的頻率統計。那麼一個word unique等同於word在兩個map裏取到的頻次是同樣的。(即要麼沒出現過取到都是0,要麼全部取到的abbr的統計都來源於dict裏這個單詞的統計數)code

細節:
1.這題unique函數裏直接寫return abbrs.get(abbr(word)) == dicts.get(word);不會有問題,不須要用getOrDefault。雖然==只對null和對象的比較有定義,基礎變量類型不能和null相比。好比Integer a = 1; a == null不報錯,但1 == null報錯。可是本題根據Map<*, Integer>的範型定義,返回的是Integer是包裝過的int是對象類型的,因此就算只有其中一個是返回null,另外一個非null,比較不會報編譯錯誤。
2.產生abbr的時候拼接第一個char+長度int+最後一個char,記得要轉其中一個爲String,不然加一加仍是一堆數字。orm

 

實現:對象

class ValidWordAbbr {

        private Map<String, Integer> abbrs = new HashMap<>();
        private Map<String, Integer> dicts = new HashMap<>();

        public ValidWordAbbr(String[] dictionary) {
            for (String s : dictionary) {
                abbrs.put(abbr(s), abbrs.getOrDefault(abbr(s), 0) + 1);
                dicts.put(s, dicts.getOrDefault(s, 0) + 1);
            }
        }

        public boolean isUnique(String word) {
            return abbrs.get(abbr(word)) == dicts.get(word);
        }

        private String abbr(String s) {
            if (s.length() <= 2) {
                return s;
            } else {
                // P1: 中間作一下類型轉換,不然會出現char+int+char仍是數字的狀況。
                return s.charAt(0) + String.valueOf(s.length() - 2) + s.charAt(s.length() - 1);
            }
        }
    }

    /**
     * Your ValidWordAbbr object will be instantiated and called as such:
     * ValidWordAbbr obj = new ValidWordAbbr(dictionary);
     * boolean param_1 = obj.isUnique(word);
     */
相關文章
相關標籤/搜索