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
Links: http://leetcode.com/problems/unique-word-abbreviation/
Exercises
The title of the new question is really getting longer. This problem is given an array dictionary, whether the input string has a unique abbreviation in dictionary. We choose to use map<string, set<string>> to do the data structure we store the data, and then we can do it according to test instructions, and we need to judge some boundary conditions, such as the abbreviation does not return true in the map directly. It is important to keep in mind that a good data structure is chosen and it is much easier to write programs.
Time Complexity-o (n * l), Space complexity-o (n * l).
Public classVALIDWORDABBR {PrivateMap<string, hashset<string>>map; Publicvalidwordabbr (string[] dictionary) { This. Map =NewHashmap<>(); for(inti = 0; i < dictionary.length; i++) {String abbr=getabbr (Dictionary[i]); if(!Map.containskey (abbr)) {HashSet<String> set =NewHashset<>(); Set.add (Dictionary[i]); Map.put (abbr, set); } Else { if(!Map.get (abbr). Contains (Dictionary[i])) {Map.get (abbr). Add (Dictionary[i]); } } } } Public BooleanIsUnique (String word) {if(map.size () = = 0 | | word.length () < 3) { return true; } String abbr=GETABBR (word); if(!map.containskey (abbr) | | (Map.get (abbr). Contains (word) && map.get (abbr). Size () = = 1)) { return true; } Else { return false; } } Privatestring Getabbr (string s) {if(S.length () < 3) { returns; } Else { returnS.substring (0, 1) + string.valueof (S.length ()-2) + s.substring (s.length ()-1); } }}//Your Validwordabbr object would be instantiated and called as such://validwordabbr VWA = new Validwordabbr (dictionary);//vwa.isunique ("Word");//vwa.isunique ("Anotherword");
Reference:
Https://leetcode.com/discuss/62842/a-simple-java-solution-using-map-string-string
Https://leetcode.com/discuss/61658/share-my-java-solution
288.Unique Word abbreviation