|
| 1 | +package easy; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.HashSet; |
| 5 | +import java.util.Iterator; |
| 6 | +import java.util.Map; |
| 7 | +import java.util.Set; |
| 8 | + |
| 9 | +public class UniqueWordAbbreviation { |
| 10 | + |
| 11 | + private class ValidWordAbbr { |
| 12 | + private Map<String, String> dict; |
| 13 | + public ValidWordAbbr(String[] dictionary) { |
| 14 | + dict = new HashMap(); |
| 15 | + for(String word : dictionary){ |
| 16 | + String key = word.length() <= 2 ? word : (word.charAt(0) + String.valueOf(word.length()-2) + word.charAt(word.length()-1)); |
| 17 | + if(dict.containsKey(key) && !dict.get(key).equals(word)){ |
| 18 | + dict.put(key, ""); |
| 19 | + } else { |
| 20 | + dict.put(key, word); |
| 21 | + } |
| 22 | + } |
| 23 | + } |
| 24 | + public boolean isUnique(String word) { |
| 25 | + String key = word.length() <= 2 ? word : (word.charAt(0) + String.valueOf(word.length()-2) + word.charAt(word.length()-1)); |
| 26 | + if(!dict.containsKey(key)) return true; |
| 27 | + else return dict.get(key) != "" && dict.get(key).equals(word); |
| 28 | + } |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +class ValidWordAbbr { |
| 33 | + |
| 34 | + private Map<String, Set<String>> dict; |
| 35 | + |
| 36 | + public ValidWordAbbr(String[] dictionary) { |
| 37 | + dict = new HashMap(); |
| 38 | + for(String word : dictionary){ |
| 39 | + String key = word.length() <= 2 ? word : (word.charAt(0) + String.valueOf(word.length()-2) + word.charAt(word.length()-1)); |
| 40 | + if(dict.containsKey(key)){ |
| 41 | + Set<String> set = dict.get(key); |
| 42 | + set.add(word); |
| 43 | + dict.put(key, set); |
| 44 | + } else { |
| 45 | + Set<String> set = new HashSet(); |
| 46 | + set.add(word); |
| 47 | + dict.put(key, set); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + public boolean isUnique(String word) { |
| 53 | + String key = word.length() <= 2 ? word : (word.charAt(0) + String.valueOf(word.length()-2) + word.charAt(word.length()-1)); |
| 54 | + if(!dict.containsKey(key)) return true; |
| 55 | + else { |
| 56 | + Set<String> set = dict.get(key); |
| 57 | + if(set.size() != 1) return false; |
| 58 | + Iterator<String> it = set.iterator(); |
| 59 | + return it.next().equals(word); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments