mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Create unique_word_abbreviation.py
This commit is contained in:
parent
0ad1ab44be
commit
696c045a16
30
arrays_and_strings/unique_word_abbreviation.py
Normal file
30
arrays_and_strings/unique_word_abbreviation.py
Normal file
@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
|
||||
'''
|
||||
The abbreviation of a word is a concatenation of its first letter,
|
||||
the number of characters between the first and last letter, and its
|
||||
last letter. If a word has only two characters, then it is an abbreviation of itself.
|
||||
Returns true if either of the following conditions are met (otherwise returns false):
|
||||
- There is no word in dictionary whose abbreviation is equal to word's abbreviation.
|
||||
- For any word in dictionary whose abbreviation is equal to word's abbreviation,
|
||||
that word and word are the same.
|
||||
'''
|
||||
|
||||
class ValidWordAbbr:
|
||||
|
||||
def __init__(self, dictionary: List[str]):
|
||||
self.dict = collections.defaultdict(set)
|
||||
for w in dictionary:
|
||||
aux_dict[self.get_abr(w)].add(w)
|
||||
return aux_dict
|
||||
|
||||
def get_abr(self, word):
|
||||
return word[0] + str(len(word[1:-1])) + word[-1] if len(word) != 2 else word
|
||||
|
||||
def isUnique(self, word: str) -> bool:
|
||||
abr = self.get_abr(word)
|
||||
words = self.dict[abr]
|
||||
return len(words) == 0 or (len(words) == 1 and word in words)
|
||||
|
Loading…
x
Reference in New Issue
Block a user