LeetCode Unique Word Abbreviation

原题链接在这里:https://leetcode.com/problems/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

题解:

把dictionary 变成HashMap<String, HashSet<String>>, key 是 abbr. value 是所有这个缩写原有词的set.

isUnique函数若是对于长度小于3的word return true. 若是HashMap没有word abbr这个key 或者 对应set只有 word这一个词也返回true.

Time Complexity: constructor O(n), n是dictionary长度. isUnique O(1). Space: O(n).

AC Java:

 1 public class ValidWordAbbr {
 2     HashMap<String, HashSet<String>> hm;
 3     public ValidWordAbbr(String[] dictionary) {
 4         hm = new HashMap<String, HashSet<String>>();
 5         for(String s : dictionary){
 6             String abbr = getAbbr(s);
 7             if(!hm.containsKey(abbr)){
 8                 HashSet<String> hs = new HashSet<String>();
 9                 hs.add(s);
10                 hm.put(abbr, hs);
11             }else{
12                 hm.get(abbr).add(s);
13             }
14         }
15     }
16 
17     public boolean isUnique(String word) {
18         if(hm.size() == 0 || word.length() < 3){
19             return true;
20         }
21         String abbr = getAbbr(word);
22         if(!hm.containsKey(abbr) || (hm.get(abbr).contains(word) && hm.get(abbr).size() == 1)){
23             return true;
24         }
25         return false;
26     }
27     
28     private String getAbbr(String s){
29         if(s == null || s.length() < 3){
30             return s;
31         }
32         return s.substring(0,1) + String.valueOf(s.length()-2) + s.substring(s.length()-1);
33     }
34 }
35 
36 
37 // Your ValidWordAbbr object will be instantiated and called as such:
38 // ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
39 // vwa.isUnique("Word");
40 // vwa.isUnique("anotherWord");

 

posted @ 2016-03-03 12:20  Dylan_Java_NYC  阅读(373)  评论(0编辑  收藏  举报