The original title link is here: https://leetcode.com/problems/unique-word-abbreviation/
Topic:
An abbreviation of a word follows the form <first letter><number><last letter>. Below is some examples of word abbreviations:
A) It --it (no abbreviation) 1b) d|o|g- d1g 1 1 1 1---5----0----5--8c) i| Nternationalizatio|n-- i18n 1 1---5----0d) l|ocalizatio|n-- l10n
Assume you has a dictionary and given a word, find whether its abbreviation are unique in the dictionary. A word ' s abbreviation is A unique if No and Word from the dictionary have the same abbreviation.
Example:
false
true
false
true
Exercises
Turn dictionary into hashmap<string, Hashset<string>> key is abbr. Value is the set of all the original words in this abbreviation.
The IsUnique function is true for word return with a length less than 3. If HashMap does not have Word abbr this key or corresponding set only word this word also returns TRUE.
Time Complexity:constructor O (n), n is the dictionary length. IsUnique O (1). Space:o (n).
AC Java:
1 Public classVALIDWORDABBR {2Hashmap<string, hashset<string>>HM;3 Publicvalidwordabbr (string[] dictionary) {4HM =NewHashmap<string, hashset<string>>();5 for(String s:dictionary) {6String abbr =Getabbr (s);7 if(!Hm.containskey (abbr)) {8hashset<string> HS =NewHashset<string>();9 Hs.add (s);Ten hm.put (abbr, HS); One}Else{ A Hm.get (abbr). Add (s); - } - } the } - - Public BooleanIsUnique (String word) { - if(hm.size () = = 0 | | word.length () < 3){ + return true; - } +String abbr =GETABBR (word); A if(!hm.containskey (abbr) | | (Hm.get (abbr). Contains (word) && hm.get (abbr). Size () = = 1)){ at return true; - } - return false; - } - - Privatestring Getabbr (string s) { in if(s = =NULL|| S.length () < 3){ - returns; to } + returnS.substring (0,1) + string.valueof (S.length ()-2) + s.substring (s.length ()-1); - } the } * $ Panax Notoginseng //Your Validwordabbr object would be instantiated and called as such: - //validwordabbr VWA = new Validwordabbr (dictionary); the //vwa.isunique ("Word"); + //vwa.isunique ("Anotherword");
Leetcode Unique Word abbreviation