FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode/java/288_Unique_Word_Abbreviation.java at master · jakehoare/leetcode · GitHub
jakehoare
/
leetcode
Public
Notifications
You must be signed in to change notification settings
Fork
30
Star
51
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode
/
java
/
288_Unique_Word_Abbreviation.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
49 lines (38 loc) · 1.84 KB
Breadcrumbs
leetcode
/
java
/
288_Unique_Word_Abbreviation.java
Copy path
File metadata and controls
49 lines (38 loc) · 1.84 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
https://leetcode.com/problems/unique-word-abbreviation/
An abbreviation of a word follows the form <first letter><number><last letter>.
Assume you have a dictionary and given a word, find whether its abbreviation is unique in the dictionary.
A word's abbreviation is unique if no other word from the dictionary has the same abbreviation.
Note that words of length less than 2 are abbreviated to themselves.
Create a map from abbreviations to words. If an abbreviation has already been used then it is mapped to the empty
String. New word has unique abbreviation if that abbreviation has not been used or has only been used to abbreviate
that word.
Time - O(n) for constructor, O(1) for isUnique()
Space - O(n)
*/
public
class
ValidWordAbbr
{
private
Map
<
String
,
String
>
map
;
// instance variable (adding static could make class variable)
public
ValidWordAbbr
(
String
[]
dictionary
) {
// constructor
map
=
new
HashMap
<
String
,
String
>();
for
(
String
word
:
dictionary
) {
String
abbreviation
=
abbreviate
(
word
);
if
(
map
.
containsKey
(
abbreviation
) && !
map
.
get
(
abbreviation
).
equals
(
word
))
// .equals() to compare Strings
map
.
put
(
abbreviation
,
""
);
else
map
.
put
(
abbreviation
,
word
);
}
}
public
boolean
isUnique
(
String
word
) {
String
abbreviation
=
abbreviate
(
word
);
return
!
map
.
containsKey
(
abbreviation
) ||
map
.
get
(
abbreviation
).
equals
(
word
);
}
public
String
abbreviate
(
String
word
) {
if
(
word
.
length
() <=
2
)
return
word
;
return
word
.
charAt
(
0
) +
Integer
.
toString
(
word
.
length
()-
2
) +
word
.
charAt
(
word
.
length
()-
1
);
}
}
// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
// vwa.isUnique("Word");
// vwa.isUnique("anotherWord");
Back
|
FazBrowse Home
|
New Git URL