Skip to content

Commit 721d2e5

Browse files
authored
Create 288. Unique Word Abbreviation
TODO: refactor lines 9-17
1 parent d8ce061 commit 721d2e5

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

288. Unique Word Abbreviation

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
public class ValidWordAbbr {
2+
Map<String, HashSet<String>> abbrs2Words;
3+
public ValidWordAbbr(String[] dictionary) {
4+
abbrs2Words = new HashMap<>();
5+
6+
for (String word : dictionary) {
7+
String k = abbr(word);
8+
9+
if (!abbrs2Words.containsKey(k)) {
10+
HashSet<String> v = new HashSet<String>();
11+
v.add(word);
12+
abbrs2Words.put(k, v);
13+
} else {
14+
HashSet<String> v = abbrs2Words.get(k);
15+
v.add(word);
16+
abbrs2Words.put(k, v);
17+
}
18+
}
19+
}
20+
21+
public boolean isUnique(String word) {
22+
String k = abbr(word);
23+
// if a new word, or the only word, then unique
24+
// otherwise, it's not
25+
if ((!abbrs2Words.containsKey(k)) ||
26+
(abbrs2Words.containsKey(k) && abbrs2Words.get(k).contains(word) && abbrs2Words.get(k).size() == 1)) {
27+
return true;
28+
}
29+
30+
return false;
31+
}
32+
33+
private String abbr(String word) {
34+
if (word.length() <= 2) {
35+
return word;
36+
} else {
37+
int len = word.length();
38+
return word.charAt(0) + String.valueOf(len - 2) + word.charAt(len-1);
39+
}
40+
}
41+
}
42+
43+
44+
// Your ValidWordAbbr object will be instantiated and called as such:
45+
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
46+
// vwa.isUnique("Word");
47+
// vwa.isUnique("anotherWord");

0 commit comments

Comments
 (0)