码迷,mamicode.com
首页 > 其他好文 > 详细

288. Unique Word Abbreviation

时间:2016-10-15 02:44:35      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

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

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

标签:

原文地址:http://www.cnblogs.com/warmland/p/5962591.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!