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
Problem Solving Ideas:
There are 3 key points to solve:
1. Find out the law of Word abbreviation, <first letter><number><last letter>,number = String.Length ()-2
2. When the same abbreviation is found in the dictionary, the value corresponding to the key becomes ""
3. The abbreviation of "Hello", i.e, H3O already exists in the dictionary.
Input: ["Hello"],isunique ("Hello") Output: [FALSE] expected: [true]
If The given word itself is in the dictionary, and it have the unique abbreviation, then we should return true.
Java Code:
Public classvalidwordabbr { private Map<string, string> map =NewHashmap<string, string>(); Publicvalidwordabbr (string[] dictionary) { for(inti = 0; i < dictionary.length; i++) {String key=abbreviate (Dictionary[i]); if(!Map.containskey (Key)) {Map.put (key, Dictionary[i]); }Else{map.put (key,""); } } } Privatestring abbreviate (String str) {returnStr.charat (0) + integer.tostring (Str.length ()-2) + Str.charat (Str.length ()-1); } Public BooleanIsUnique (string word) {string x=abbreviate (word); if(Map.containskey (x)) {if(Map.get (x). Equals (Word)) {return true; }Else { return false; } } return true; }}//Your Validwordabbr object would be instantiated and called as such://validwordabbr VWA = new Validwordabbr (dictionary);//vwa.isunique ("Word");//vwa.isunique ("Anotherword");
Reference:
1. https://leetcode.com/discuss/62842/a-simple-java-solution-using-map-string-string
2. Https://leetcode.com/discuss/62824/wrong-test-case
Leetcode Unique Word abbreviation