原题网址:https://leetcode.com/problems/unique-word-abbreviation/
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
方法:比较直接的方法,就是建立哈希映射,以缩写为key,以原始的单词为value。
public class ValidWordAbbr {
private Map<String, Set<String>> abbrs = new HashMap<>();
private String abbr(String word) {
if (word.length() <= 2) return word;
StringBuilder sb = new StringBuilder();
sb.append(word.charAt(0));
sb.append(word.length()-2);
sb.append(word.charAt(word.length()-1));
return sb.toString();
}
public ValidWordAbbr(String[] dictionary) {
for(String word: dictionary) {
String abbr = abbr(word);
Set<String> words = abbrs.get(abbr);
if (words == null) {
words = new HashSet<>();
abbrs.put(abbr, words);
}
words.add(word);
}
}
public boolean isUnique(String word) {
Set<String> words = abbrs.get(abbr(word));
if (words == null || words.isEmpty()) return true;
if (words.size() == 1 && words.contains(word)) return true;
return false;
}
}
// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
// vwa.isUnique("Word");
// vwa.isUnique("anotherWord");
方法二:可以优化不使用哈希集合。
public class ValidWordAbbr {
private Map<String, Abbr> map = new HashMap<>();
private String abbr(String word) {
if (word == null || word.length() <=2) return word;
return word.substring(0,1) + Integer.toString(word.length()-2) + word.substring(word.length()-1);
}
public ValidWordAbbr(String[] dictionary) {
for(String word: dictionary) {
String key = abbr(word);
Abbr abbr = map.get(key);
if (abbr == null) abbr = new Abbr(word);
else if (!word.equals(abbr.word)) abbr.count ++;
map.put(key, abbr);
}
}
public boolean isUnique(String word) {
Abbr abbr = map.get(abbr(word));
if (abbr == null) return true;
if (abbr.count > 1) return false;
if (abbr.word.equals(word)) return true;
return false;
}
}
class Abbr {
int count;
String word;
Abbr(String word) {
this.word = word;
this.count = 1;
}
}
// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
// vwa.isUnique("Word");
// vwa.isUnique("anotherWord");