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
Solution: run time complexity is O(n), space complexity is O(n).public class ValidWordAbbr {
HashMap> map = new HashMap>();
public ValidWordAbbr(String[] dictionary) {
for (String s : dictionary) {
if (s == null || s.length() == 0) {
continue;
}
if (!map.containsKey(getAbbr(s))) {
ArrayList list = new ArrayList();
list.add(s);
map.put(getAbbr(s), list);
} else {
if (!map.get(getAbbr(s)).contains(s)) {
map.get(getAbbr(s)).add(s);
}
}
}
}
public boolean isUnique(String word) {
if (word == null || word.length() == 0) {
return true;
}
String key = getAbbr(word);
if(!map.containsKey(key)) {
return true;
} else {
if (map.get(key).size() == 1 && map.get(key).get(0).equals(word)) { // dictionary[hello], word="hello" -> unique
return true;
}
}
return false;
}
public String getAbbr(String str) {
if (str.length() <= 2) {
return str;
}
return str.charAt(0) + String.valueOf(str.length() - 2) + str.charAt(str.length() - 1);
}
}
// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
// vwa.isUnique("Word");
// vwa.isUnique("anotherWord");
No comments:
Post a Comment