spiralgo / algorithms

We voluntarily solve algorithm problems on this repo.
24 stars 7 forks source link

527. Word Abbreviation #379

Closed ErdemT09 closed 3 years ago

ErdemT09 commented 3 years ago

Resolves: #214

Algorithm:

In order to fix the duplicate abbreviation situation stated in the problem, we simply begin by abbreviating all the words as they would be without considering the other words. For each abbreviation, we put it as a key into a map and add the word that it is abbreviated from. Thus, this map stores which abbreviations correspond to which words, so we can see the duplicates.

After that, for each word, we check if the entry of its abbreviation in the map contains duplicate (its list having a size >1). If so, we distribute these words into new abbreviations by incrementing their prefix. For the words "spiralgo", the old abbreviation "s6o" will become "sp5o". If a word like "smnbgfdo" had the same abbreviation "s6o", we would also remake it to "sm5o". After doing this re-abbreviating, we check the word again. If there are still duplicates (for example "spwwwwwo" becoming "sp5o" too) we reabbreviate again until there are no duplicates left, or we run out of letters.