Leetcode 527 Solution

This article provides solution to leetcode question 527 (word-abbreviation)

https://leetcode.com/problems/word-abbreviation

Solution

class Solution:
    def wordsAbbreviation(self, words: List[str]) -> List[str]:
        def make_abbv(word, prefix_len):
            if prefix_len + 2 >= len(word):
                return word

            return word[:prefix_len] + str(len(word) - prefix_len - 1) + word[-1:]

        prefix_lens = [1] * len(words)
        res = [make_abbv(word, 1) for word in words]

        for i, word in enumerate(words):
            while True:
                dup_set = set()

                for j in range(i + 1, len(words)):
                    if res[i] == res[j]:
                        dup_set.add(j)

                if not dup_set:
                    break

                dup_set.add(i)

                for k in dup_set:
                    prefix_lens[k] += 1
                    res[k] = make_abbv(words[k], prefix_lens[k])

        return res