288. 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:hashmap

思路:前提遍歷存好(abr_key -> str)的map,如果有重復(fù),將str置為""使之無效這樣要判斷的同key的str和它一定不相等,return false。
Time Complexity: 初始化構(gòu)造O(N) isUnique(): O(1) Space Complexity: O(N)

Solution Code:

public class ValidWordAbbr {
    HashMap<String, String> map;
    public ValidWordAbbr(String[] dictionary) {
        map = new HashMap<String, String>();
        for(String str: dictionary){
            String key = getKey(str);
            // If there is more than one string belong to the same key
            // then the key will be invalid, we set the value to ""
            if(map.containsKey(key)){
                if(!map.get(key).equals(str)){
                    map.put(key, "");
                }
            }
            else{
                map.put(key, str);
            }
        }
    }

    public boolean isUnique(String word) {
        return !map.containsKey(getKey(word)) || map.get(getKey(word)).equals(word);
    }
    
    String getKey(String str){
        if(str.length() <= 2) return str;
        return str.charAt(0)+Integer.toString(str.length() - 2)+str.charAt(str.length() - 1);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,916評論 0 33
  • 簡單的說,一個(gè)對象(在學(xué)習(xí)設(shè)計(jì)模式之前,需要比較了解面向?qū)ο笏枷耄┲回?fù)責(zé)一個(gè)特定的任務(wù); 單例類: 1、構(gòu)造函數(shù)需...
    人在碼途閱讀 182評論 0 1
  • 接入Android SDK流程分為以下四步: 寫Android Activity文件 與 unity的調(diào)用java...
    云木unity閱讀 3,356評論 2 8
  • 三年前結(jié)束了米蘿咖啡,離開了清溪,我以為,我再也不會重新踏上這塊土地。偶然的機(jī)會,經(jīng)朋友的介紹,我又重歸清溪了,為...
    藍(lán)小獸閱讀 309評論 0 2
  • 今天拍照,突然發(fā)現(xiàn),我所能會拍的也就是這些花花草草,攝影的層次還只是停留在淺層,未作深沉思考,我究竟想要表達(dá)什么主...
    卿瑩閱讀 198評論 0 0

友情鏈接更多精彩內(nèi)容