[Leetcode] 320. Generalized Abbreviation 解题报告

本文介绍了一种使用回溯法生成单词所有可能的缩写形式的方法。针对输入单词,通过两种选择(转换为数字或保留字母)进行深度优先搜索,最终得到所有可能的缩写组合。

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

题目

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

Example:

Given word = "word", return the following list (order does not matter):

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

思路

凡是返回解集合的题目大多数都可以用回溯法求解,本题目也不例外。对于单词word的第i个字符word[i],我们有两种处理方法:1)将word[i]转化为数字缩写;2)保留word[i]。这两种情况构成了DFS的两个搜索分支。当然在返回结果的时候,别忘了在num不为0的情况下,将其加入缩写结果的尾部。

代码

class Solution {
public:
    vector<string> generateAbbreviations(string word) {
        vector<string> ret;
        DFS(word, 0, ret, "", 0);
        return ret;
    }
private:
    void DFS(string& word, int pos, vector<string>& ret, string line, int num) {
        if(pos == word.length()) {
            if(num != 0) {
                line += to_string(num);
            }
            ret.push_back(line);
            return;
        }
        DFS(word, pos + 1, ret, line, num + 1);                                             // abbreviate word[pos]
        DFS(word, pos + 1, ret, line + (num == 0 ? "" : to_string(num)) + word[pos], 0);    // keep word[pos]
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值