Last active
April 15, 2016 03:00
-
-
Save cangoal/c0918d710e045c8d585254099943762a to your computer and use it in GitHub Desktop.
LeetCode - Unique Word Abbreviation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
public class ValidWordAbbr { | |
private Map<String, Integer> map; | |
private Map<String, Integer> dict; | |
public ValidWordAbbr(String[] dictionary) { | |
map = new HashMap<String, Integer>(); | |
dict = new HashMap<String, Integer>(); | |
for(String word : dictionary){ | |
String key = abbreviate(word); | |
if(!map.containsKey(key)){ | |
map.put(key, 0); | |
} | |
map.put(key, map.get(key) + 1); | |
if(!dict.containsKey(word)){ | |
dict.put(word, 0); | |
} | |
dict.put(word, dict.get(word) + 1); | |
} | |
} | |
private String abbreviate(String word){ | |
if(word == null || word.length() < 3) return word; | |
int len = word.length() - 2; | |
StringBuilder sb = new StringBuilder(); | |
sb.append(word.charAt(0)); | |
sb.append(len); | |
sb.append(word.charAt(len + 1)); | |
return sb.toString(); | |
} | |
public boolean isUnique(String word) { | |
if(word == null) return false; | |
String key = abbreviate(word); | |
if(!dict.containsKey(word)){ | |
if(map.containsKey(key)) return false; | |
else return true; | |
} else{ | |
return map.get(key) == dict.get(word); | |
} | |
} | |
} | |
// Your ValidWordAbbr object will be instantiated and called as such: | |
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary); | |
// vwa.isUnique("Word"); | |
// vwa.isUnique("anotherWord"); | |
// https://leetcode.com/discuss/86526/let-me-explain-the-question-with-better-examples | |
// better solution https://leetcode.com/discuss/71652/java-solution-with-hashmap-string-string-beats-submissions |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment