288. Unique Word Abbreviation

Posted warmland

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了288. Unique Word Abbreviation相关的知识,希望对你有一定的参考价值。

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

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 }

 

以上是关于288. Unique Word Abbreviation的主要内容,如果未能解决你的问题,请参考以下文章

java 288. Unique Word Abbreviation.java

java 288. Unique Word Abbreviation.java

java 288. Unique Word Abbreviation.java

java 288. Unique Word Abbreviation.java

288. Unique Word Abbreviation

288. Unique Word Abbreviation