288. Unique Word Abbreviation

LeetCode单词缩写验证
本文介绍了一种使用HashMap来解决LeetCode上单词缩写验证问题的方法。通过存储每个缩写及其对应的原始单词,可以快速判断一个新单词的缩写是否唯一。如果缩写已经存在且不对应相同的原始单词,则该缩写不唯一。

这是一题非常坑的简单题。

https://discuss.leetcode.com/topic/37254/let-me-explain-the-question-with-better-examples/2

1) [“dog”]; isUnique(“dig”);   

//False, because “dig” has the same abbreviation with “dog" and “dog” is already in the dictionary. It’s not unique.

2) [“dog”, “dog"]; isUnique(“dog”);  

//True, because “dog” is the only word that has “d1g” abbreviation.

3) [“dog”, “dig”]; isUnique(“dog”);   

//False, because if we have more than one word match to the same abbreviation, this abbreviation will never be unique.

这样就能明白了

 

 思路:

  建一个Hashmap,key是缩写,value是对应的词,如果对词典进行建立的时候就已经发现重复了,就把value设置成“”

  对新来的词,如果这个词的缩写在map并且这个词不是那个字典里产生这个词的原词,那么就返回false。

 1 public class ValidWordAbbr {
 2     Map<String, String> dic;
 3 
 4     public ValidWordAbbr(String[] dictionary) {
 5         dic = new HashMap<String, String>();
 6         for(int i = 0; i < dictionary.length; i++) {
 7             String abb = generateAbb(dictionary[i]);
 8             if(dic.containsKey(abb) && !dic.get(abb).equals(dictionary[i])) {
 9                 dic.put(abb, "");
10             } else {
11                 dic.put(abb, dictionary[i]);
12             }
13         }
14     }
15     
16     private String generateAbb(String s) {
17         int len = s.length();
18         if(len < 3) {
19             return s;
20         }
21         StringBuilder sb = new StringBuilder();
22         sb.append(s.charAt(0));
23         sb.append(len - 2);
24         sb.append(s.charAt(len - 1));
25         return sb.toString();
26     }
27 
28     public boolean isUnique(String word) {
29         String abb = generateAbb(word);
30         return !dic.containsKey(abb) || dic.get(abb).equals(word);
31     }
32 }

 

转载于:https://www.cnblogs.com/warmland/p/5962591.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值