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:
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:
isUnique("cart") ->
isUnique("cane") ->
isUnique("make") ->
Solution:[/code]
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");
相关文章推荐
- Leetcode Unique Word Abbreviation
- Leetcode: Unique Word Abbreviation
- LeetCode 256. Unique Word Abbreviation
- [Leetcode 411]Minimum Unique Word Abbreviation
- Leetcode Unique Word Abbreviation
- LeetCode 411: Minimum Unique Word Abbreviation
- [Leetcode] 411. Minimum Unique Word Abbreviation 解题报告
- Leetcode Unique Word Abbreviation
- [leetcode 288] Unique Word Abbreviation
- [LeetCode288]Unique Word Abbreviation
- [LeetCode] Unique Word Abbreviation
- *LeetCode-Unique Word Abbreviation
- [LeetCode] Unique Word Abbreviation 独特的单词缩写
- [LeetCode] Unique Word Abbreviation
- Leetcode: Minimum Unique Word Abbreviation
- leetcode 288: Unique Word Abbreviation
- [LeetCode] Minimum Unique Word Abbreviation 最短的独一无二的单词缩写
- LeetCode Unique Word Abbreviation
- [Locked] Unique Word Abbreviation
- Unique Word Abbreviation