Advertisement
lifeiteng

288. Unique Word Abbreviation

Sep 24th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.99 KB | None | 0 0
  1. class ValidWordAbbr {
  2.  
  3.     Set<String> set = new HashSet<>();
  4.     Map<String, Integer> map = new HashMap<>();
  5.    
  6.     public ValidWordAbbr(String[] dictionary) {
  7.         for(String w : dictionary)
  8.         {
  9.             if(set.contains(w)) continue;
  10.             String str = shorten(w);
  11.             set.add(w);
  12.             map.put(str, map.getOrDefault(str, 0) + 1);
  13.         }    
  14.     }
  15.    
  16.     String shorten(String str)
  17.     {
  18.         int n = str.length();
  19.         if(n < 3) return str;
  20.         return "" + str.charAt(0) + (n - 2) + str.charAt(n - 1);
  21.     }
  22.    
  23.     public boolean isUnique(String word) {
  24.         String str = shorten(word);
  25.         if(set.contains(word) && map.get(str) < 2) return true;
  26.         if(!set.contains(word) && !map.containsKey(str)) return true;
  27.         return false;
  28.     }
  29. }
  30.  
  31. /**
  32.  * Your ValidWordAbbr object will be instantiated and called as such:
  33.  * ValidWordAbbr obj = new ValidWordAbbr(dictionary);
  34.  * boolean param_1 = obj.isUnique(word);
  35.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement