【精】LintCode领扣算法问题答案:648. 单词缩写集
发布日期:2021-06-30 17:13:36 浏览次数:2 分类:技术文章

本文共 2216 字,大约阅读时间需要 7 分钟。

648. 单词缩写集

描述

一个单词的缩写根据以下的形式。下面是一些缩写的例子

a) it                      --> it    (没有缩写) 	 1b) d|o|g                   --> d1g          	  1    1  1   	 1---5----0----5--8c) i|nternationalizatio|n  --> i18n          	  1 	 1---5----0d) l|ocalizatio|n          --> l10n

假设你有一个字典和给你一个单词,判断这个单词的缩写在字典中是否是唯一的。当字典中的其他单词的缩写均与它不同的时候, 这个单词的缩写是唯一的.

样例 1:

输入:	[ "deer", "door", "cake", "card" ]	isUnique("dear")	isUnique("cart")输出:	false	true解释:	字典中所有单词的缩写为 ["d2r", "d2r", "c2e", "c2d"].	"dear" 的缩写是 "d2r" , 在字典中。	"cart" 的缩写是 "c2t" , 不在字典中。

样例 2:

输出:	isUnique("cane")	isUnique("make")输出:	false	true解释:	字典中所有单词的缩写为 ["d2r", "d2r", "c2e", "c2d"].	"cane" 的缩写是 "c2e" , 在字典中。	"make" 的缩写是 "m2e" , 不在字典中。


文章目录


题解

public class ValidWordAbbr {
private final Set
dictionary; private final Map
counter; /* * @param dictionary: a list of words */ public ValidWordAbbr(String[] dictionary) {
// do intialization if necessary this.dictionary = new HashSet<>(); this.counter = new HashMap<>(); for (String word : dictionary) {
this.dictionary.add(word); if (word.length() > 2) {
String s = "" + word.charAt(0) + (word.length() - 2) + word.charAt(word.length() - 1); counter.put(s, counter.getOrDefault(s, 0) + 1); } } } /* * @param word: a string * @return: true if its abbreviation is unique or false */ public boolean isUnique(String word) {
// write your code here if (word.length() <= 2) {
return true; } String s = "" + word.charAt(0) + (word.length() - 2) + word.charAt(word.length() - 1); Integer count = counter.get(s); if (count == null) {
return true; } if (count > 1) {
return false; } return dictionary.contains(word); }}/** * Your ValidWordAbbr object will be instantiated and called as such: * ValidWordAbbr obj = new ValidWordAbbr(dictionary); * boolean param = obj.isUnique(word); */

最后说两句

非常感谢你阅读本文章,如果你觉得本文对你有所帮助,请留下你的足迹,点个赞,留个言,多谢~

作者水平有限,如果文章内容有不准确的地方,请指正。

希望小伙伴们都能每天进步一点点。

声明

本文由博客原创,转载请注明来源,谢谢~

转载地址:https://le-yi.blog.csdn.net/article/details/114826694 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【精】LintCode领扣算法问题答案:1303. H指数 II
下一篇:LintCode领扣算法问题答案:645. 识别名人

发表评论

最新留言

不错!
[***.144.177.141]2024年04月21日 05时25分41秒