LeetCode 320. Generalized Abbreviation 去重

本文介绍了一种生成单词所有可能的缩写形式的方法,通过两种不同的算法实现:一种是深度优先搜索(DFS)策略,另一种是利用二进制位操作。这两种方法都能有效地生成如输入单词word的所有缩写组合,包括1ord、w1rd等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Write a function to generate the generalized abbreviations of a word. 

Note: The order of the output does not matter.

Example:

Input: "word"
Output:
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]

-------------------------------------------------------------------------------

The key for this problem is to remove duplicates:

set a number, arrange a character after the number, +some possibility in the following combinations:

class Solution:
    def generateAbbreviations(self, word):
        def dfs(w):
            l,res = len(w),[w]
            for last in range(l):
                for first in range(last+1):
                    #[first:last+1]:num, [last+1,last+2]:ch, [last+2:]
                    for rest in dfs(w[last+2:]):
                        res.append(w[:first]+str(last-first+1)+w[last+1:last+2]+rest)
            return res
        ret = dfs(word)
        return ret

s = Solution()
print(s.generateAbbreviations("word"))

Second solution, use binary:

class Solution:
    def generateAbbreviations(self, word):
        def get_abb(word, binary, l):
            cnt = 0
            res = ""
            for i in range(l):
                if (binary & (1 << (l-i-1))):
                    if (cnt > 0):
                        res += str(cnt)
                    res += word[i]
                    cnt = 0
                else:
                    cnt += 1
            if (cnt > 0):
                res += str(cnt)
            return res
        res = []
        lw = len(word)
        for i in range(1<<lw):
            res.append(get_abb(word, i, lw))
        return res

s = Solution()
print(s.generateAbbreviations("word"))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值