Leetcode: Unique Word Abbreviation
LeetCode word unique
2023-09-11 14:14:07 时间
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
要注意一种情况:isUnique("cake"), 应该是true. 虽然他的缩写在afterabbr出现,但是那就是他自己,没有别的跟他一样
1 public class ValidWordAbbr { 2 String[] dict; 3 HashMap<String, Set<String>> afterAbbr; 4 5 public ValidWordAbbr(String[] dictionary) { 6 this.dict = dictionary; 7 this.afterAbbr = new HashMap<String, Set<String>>(); 8 for (String item : dictionary) { 9 String str = abbr(item); 10 if (afterAbbr.containsKey(str)) { 11 afterAbbr.get(str).add(item); 12 } 13 else { 14 HashSet<String> set = new HashSet<String>(); 15 set.add(item); 16 afterAbbr.put(str, set); 17 } 18 } 19 } 20 21 public boolean isUnique(String word) { 22 String str = abbr(word); 23 if (!afterAbbr.containsKey(str)) return true; 24 else if (afterAbbr.containsKey(str) && afterAbbr.get(str).contains(word) && afterAbbr.get(str).size()==1) return true; 25 return false; 26 } 27 28 public String abbr(String item) { 29 if (item == null) return null; 30 if (item.length() <= 2) return item; 31 StringBuffer res = new StringBuffer(); 32 res.append(item.charAt(0)); 33 res.append(item.length()-2); 34 res.append(item.charAt(item.length()-1)); 35 return res.toString(); 36 } 37 } 38 39 40 // Your ValidWordAbbr object will be instantiated and called as such: 41 // ValidWordAbbr vwa = new ValidWordAbbr(dictionary); 42 // vwa.isUnique("Word"); 43 // vwa.isUnique("anotherWord");
相关文章
- [LeetCode] Length of Last Word - 最后一个单词的长度
- Java实现 LeetCode 749 隔离病毒(DFS嵌套)
- Java实现 LeetCode 650 只有两个键的键盘(递归 || 数学)
- Java实现 LeetCode 564 寻找最近的回文数(今天要GG在这道题了 头晕+题难(((φ(◎ロ◎;)φ))))...
- Java实现 LeetCode 345 反转字符串中的元音字母
- Java实现 LeetCode 123 买卖股票的最佳时机 III(三)
- Java实现 LeetCode 81 搜索旋转排序数组 II(二)
- LeetCode(81): 搜索旋转排序数组 II
- LeetCode(107): 二叉树的层次遍历 II
- LeetCode(36): 有效的数独
- 〖Python自动化办公篇⑨〗- word文件自动化 - 设置Word全局样式和文本样式
- 【LeetCode Python实现】33. 搜索旋转排序数组(中等)
- Word Ladder II [leetcode]
- Leetcode - CopyWithRandomList
- leetcode - Word Ladder
- leetcode 720. Longest Word in Dictionary
- leetcode 561. Array Partition I
- OpenXml操作Word的一些操作总结.无word组件生成word.(转)
- 【LeetCode】105. 从前序与中序遍历序列构造二叉树