LeetCode 320. Generalized Abbreviation

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”]

思路:
1. 罗列所有可能性,用for+dfs的方式搞定!和普通的for+dfs比,这个题还是稍微复杂了,需要双重for+dfs。第一层标记简写开始的坐标位置,第二层表示简写的长度。所以,要习惯看到不同的层次,比如,”1or1”,第一个1是第一层,后一个1则是第二层。
2. 根据给的所有可能组合,需要能看出这是双重for+dfs的情况,因为必须用两个独立的变量来表示所有情况,即:简化起始位置可变,简化长度可变!!

vector<string> generateAbbreviations(string word) {
    //for+dfs
    vector<string> res;
    res.push_back(word);
    dfs(word,res,0);
    return res;
}

void dfs(string word,vector<string>&res, int i){

    for(int pos=i;pos<word.size();pos++){
        string cur=word.substr(0,i);
        for(int len=1;len+pos<word.size();len++){
            cur+=to_string(len);//防止len>=10
            cur+=word.substr(i+len);
            res.push_back(cur);
            dfs(cur,res,pos+1+to_string(len).size());//pos+1+to_string(len).size()这个是计算下一层次的双重循环的开始位置!
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值