From 696c045a16621fa11cb6d62bc58e801609a3b9d6 Mon Sep 17 00:00:00 2001 From: Marina S <138340846+bt3gl-google@users.noreply.github.com> Date: Sun, 30 Jul 2023 20:22:30 -0700 Subject: [PATCH] Create unique_word_abbreviation.py --- .../unique_word_abbreviation.py | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 arrays_and_strings/unique_word_abbreviation.py diff --git a/arrays_and_strings/unique_word_abbreviation.py b/arrays_and_strings/unique_word_abbreviation.py new file mode 100644 index 0000000..e7f097c --- /dev/null +++ b/arrays_and_strings/unique_word_abbreviation.py @@ -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) +