博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode Unique Word Abbreviation
阅读量:5095 次
发布时间:2019-06-13

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

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)     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

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") -> falseisUnique("cart") -> trueisUnique("cane") -> falseisUnique("make") -> true

解题思路:

解题关键点有3个:

1. 找出word abbreviation 的规律,<first letter><number><last letter>,number = string.length() - 2

2. 当发现dictionary 里有相同的abbreviation, key 对应的value 变为"" 

3. The abbreviation of "hello", i.e., h3o already exists in the dictionary.

Input: ["hello"],isUnique("hello") Output: [false] Expected: [true]

If the given word itself is in the dictionary, and it has the unique abbreviation, then we should return true.


Java code:

public class ValidWordAbbr {    private Map
map = new HashMap
(); public ValidWordAbbr(String[] dictionary) { for(int i = 0; i < dictionary.length; i++){ String key = abbreviate(dictionary[i]); if(!map.containsKey(key)){ map.put(key, dictionary[i]); }else{ map.put(key, ""); } } } private String abbreviate(String str){ return str.charAt(0) + Integer.toString(str.length() - 2)+ str.charAt(str.length()-1); } public boolean isUnique(String word) { String x = abbreviate(word); if(map.containsKey(x)){ if(map.get(x).equals(word)){ return true; }else { return false; } } return true; }}// Your ValidWordAbbr object will be instantiated and called as such:// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);// vwa.isUnique("Word");// vwa.isUnique("anotherWord");

Reference:

1. https://leetcode.com/discuss/62842/a-simple-java-solution-using-map-string-string

2. https://leetcode.com/discuss/62824/wrong-test-case

 

转载于:https://www.cnblogs.com/anne-vista/p/4869172.html

你可能感兴趣的文章
struts.convention.classes.reload配置为true,tomcat启动报错
查看>>
IOS push消息的数字不减少的问题
查看>>
mysql报错Multi-statement transaction required more than 'max_binlog_cache_size' bytes of storage
查看>>
MySQL的并行复制多线程复制MTS(Multi-Threaded Slaves)
查看>>
Django中间件
查看>>
asp.net5 操作Cookie
查看>>
android应用开发全程实录-用户界面部分章节-你真的会用最简单的TextView么?
查看>>
学习资源
查看>>
bzoj1413: [ZJOI2009]取石子游戏
查看>>
Semaphore 简介
查看>>
keil中如何得知所编译程序所占空间大小?
查看>>
数组相关和卷积运算的实现
查看>>
bootstrap 响应式工具
查看>>
Python基础知识笔记(三)
查看>>
#define总结汇总
查看>>
图片翻转3D效果
查看>>
[PHP100]留言板(一)
查看>>
实验七1
查看>>
线程优先级问题
查看>>
HDU 1074 Doing Homework (dp+状态压缩)
查看>>