leetcode - 527. Word Abbreviation

这篇文章讨论了一个算法问题,给定一组不重复的英文单词,要求生成每个单词的最小可能缩写,使得所有缩写独特且尽可能地缩短单词。通过增加前缀长度来区分具有相同初始缩写的单词。
摘要由CSDN通过智能技术生成

Description

Given an array of distinct strings words, return the minimal possible abbreviations for every word.

The following are the rules for a string abbreviation:

  1. The initial abbreviation for each word is: the first character, then the number of characters in between, followed by the last character.
  2. If more than one word shares the same abbreviation, then perform the following operation:
    • Increase the prefix (characters in the first part) of each of their abbreviations by 1.
      • For example, say you start with the words [“abcdef”,“abndef”] both initially abbreviated as “a4f”. Then, a sequence of operations would be [“a4f”,“a4f”] -> [“ab3f”,“ab3f”] -> [“abc2f”,“abn2f”].
    • This operation is repeated until every abbreviation is unique.
  3. At the end, if an abbreviation did not make a word shorter, then keep it as the original word.

Example 1:

Input: words = ["like","god","internal","me","internet","interval","intension","face","intrusion"]
Output: ["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"]

Example 2:

Input: words = ["aa","aaa"]
Output: ["aa","aaa"]

Constraints:

1 <= words.length <= 400
2 <= words[i].length <= 400
words[i] consists of lowercase English letters.
All the strings of words are unique.

Solution

Just code intuitively… Write a function for doing the abbreviation, and then use a dict, with the key as the abbreviation, and value as the list of common words indexes. Every time add the list with length 1, and keep expanding those list with length more than 1.

Code

class Solution:
    def wordsAbbreviation(self, words: List[str]) -> List[str]:
        def abbrev(s: str, prefix_len: int) -> str:
            abbr = f'{s[:prefix_len]}{len(s) - prefix_len - 1}{s[-1]}'
            if len(abbr) >= len(s):
                abbr = s
            return abbr
        # key: abbr, value: [index1, index2, ...]}
        abbr_info = {}
        cur_prefix = 1
        # init abbr_info
        for i in range(len(words)):
            abbr = abbrev(words[i], cur_prefix)
            if abbr not in abbr_info:
                abbr_info[abbr] = []
            abbr_info[abbr].append((i, abbr))
        res = []
        while abbr_info:
            new_abbr_info = {}
            cur_prefix += 1
            for each_abbr, same_list in abbr_info.items():
                if len(same_list) == 1:
                    res.append(same_list[0])
                else:
                    for index, _ in same_list:
                        new_abbr = abbrev(words[index], cur_prefix)
                        if new_abbr not in new_abbr_info:
                            new_abbr_info[new_abbr] = []
                        new_abbr_info[new_abbr].append((index, new_abbr))
            abbr_info = new_abbr_info
        res.sort(key=lambda x:x[0])
        return list(item[1] for item in res)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值