[
string
hash table
design
]
Leetcode 0288. Unique Word Abbreviation
Problem statement
https://leetcode.com/problems/unique-word-abbreviation/
Solution
In python just create default dict with connections abbreviation $\to$ all possible words with this abbreviation. Be careful, we need to handle 2 cases: if new word already in our defaultdict and not.
Complexity
Time and memory complexity is $O(n)$, where $n$ is total length of dictionary
and all word
queries.
Code
class ValidWordAbbr:
def abbreviate(self, word):
if len(word) <= 2: return word
return word[0] + str(len(word) - 2) + word[-1]
def __init__(self, dictionary):
self.dic = defaultdict(set)
for word in dictionary:
self.dic[self.abbreviate(word)].add(word)
def isUnique(self, word):
abb = self.abbreviate(word)
if abb not in self.dic:
return True
else:
if len(self.dic[abb]) >= 2:
return False
else:
return list(self.dic[abb])[0] == word