Skip to content

Commit f3e8172

Browse files
authored
Update 288. Unique Word Abbreviation
1 parent 721d2e5 commit f3e8172

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

288. Unique Word Abbreviation

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,34 @@ public class ValidWordAbbr {
4545
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
4646
// vwa.isUnique("Word");
4747
// vwa.isUnique("anotherWord");
48+
49+
50+
// Shorter solution for ref (https://discuss.leetcode.com/topic/30533/java-solution-with-one-hashmap-string-string-beats-90-of-submissions/2)
51+
public class ValidWordAbbr {
52+
HashMap<String, String> map;
53+
public ValidWordAbbr(String[] dictionary) {
54+
map = new HashMap<String, String>();
55+
for(String str:dictionary){
56+
String key = getKey(str);
57+
// If there is more than one string belong to the same key
58+
// then the key will be invalid, we set the value to ""
59+
if(map.containsKey(key)){
60+
if(!map.get(key).equals(str)){
61+
map.put(key, "");
62+
}
63+
}
64+
else{
65+
map.put(key, str);
66+
}
67+
}
68+
}
69+
70+
public boolean isUnique(String word) {
71+
return !map.containsKey(getKey(word))||map.get(getKey(word)).equals(word);
72+
}
73+
74+
String getKey(String str){
75+
if(str.length()<=2) return str;
76+
return str.charAt(0)+Integer.toString(str.length()-2)+str.charAt(str.length()-1);
77+
}
78+
}

0 commit comments

Comments
 (0)