您的位置:首页 > 产品设计 > UI/UE

LeetCode-Unique Word Abbreviation

2016-08-30 08:29 435 查看
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") -> [code]false

isUnique("cart") ->
true

isUnique("cane") ->
false

isUnique("make") ->
true


Solution:[/code]

public class ValidWordAbbr {
Map<String, String> abbrMap;

public ValidWordAbbr(String[] dictionary) {
abbrMap = new HashMap<String, String>();

for (String word : dictionary) {
String abbr = getAbbr(word);
// the abbr is invalid, if it exsits and the corresponding word is not current word.
if (abbrMap.containsKey(abbr) && !abbrMap.get(abbr).equals(word)) {
abbrMap.put(abbr, "");
} else {
abbrMap.put(abbr, word);
}
}
}

public boolean isUnique(String word) {
String abbr = getAbbr(word);
// true, if @abbr does not exsit or the corresponding word is the @word.
return (!abbrMap.containsKey(abbr)) || (abbrMap.containsKey(abbr) && abbrMap.get(abbr).equals(word));
}

public String getAbbr(String word){
if (word.length()<=2) return word;

StringBuilder builder = new StringBuilder();
builder.append(word.charAt(0));
builder.append(word.length()-2);
builder.append(word.charAt(word.length()-1));

return builder.toString();
}
}

// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
// vwa.isUnique("Word");
// vwa.isUnique("anotherWord");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: