288. Unique Word Abbreviation

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---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 nootherword from the dictionary has the same abbreviation.
Example:
Given dictionary = [ "deer", "door", "cake", "card" ]isUnique("dear") ->falseisUnique("cart") ->trueisUnique("cane") ->falseisUnique("make") ->true

這題太惡心了, 一刷就各種整不明白, 寫了一堆堆惡心代碼, 最后還不對, 今天看攻略發現不但要邏輯正確, 還對代碼的簡潔度有要求。 尼瑪, 這條路太難走了, 全是坎兒啊,竟是坑。

看了大神答案, 代碼如下:

說一下思路, 把抽象出來的字符串作為key, 只出現一次這樣的抽象字符串就存起來, 如果有多個不用字符共享同一個抽象字符, 那么將value設置為空, 表示這個抽象串已經不是unique了。方便判斷。

剛開始把共享的字符串們放到set集合里去, 然后判斷,看完別人代碼發現尼瑪真蠢!

HashMap<String, String> map;
public ValidWordAbbr(String[] dictionary) {
? ? ? ? map = new HashMap<>();
? ? ? ? for(String str : dictionary){
? ? ? ? ? ? ? ?String key = getabs(str);
? ? ? ? ? ? ? ?if(map.containsKey(key)){
? ? ? ? ? ? ? ? ? ? ? ?if(!map.get(key).equals(str)){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? map.put(key, "");
? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ?}else{
? ? ? ? ? ? ? ? ? ? ? ? map.put(key, str);
? ? ? ? ? ? ? ?}
? ? ? ? ?}
}
public boolean isUnique(String word) {
? ? ? ? String key = getabs(word);
? ? ? ? return !map.containsKey(key) || map.get(key).equals(word);
?}
private String getabs(String word){
? ? ? ? int length =word.length();
? ? ? ? return length <= 2 ? word : word.charAt(0) + String.valueOf(length -2) + word.charAt(length-1);
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容