LintCode 779: Generalized Abbreviation

  1. Generalized Abbreviation

Write a function to generate the generalized abbreviations of a word.(order does not matter)

Example
Example 1:

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

Input:
word = “today”
Output:
[“1o1a1”,“1o1ay”,“1o2y”,“1o3”,“1od1y”,“1od2”,“1oda1”,“1oday”,“2d1y”,“2d2”,“2da1”,“2day”,“3a1”,“3ay”,“4y”,“5”,“t1d1y”,“t1d2”,“t1da1”,“t1day”,“t2a1”,“t2ay”,“t3y”,“t4”,“to1a1”,“to1ay”,“to2y”,“to3”,“tod1y”,“tod2”,“toda1”,“today”]

解法1:BFS
注意对每个pos,都要有i,j两层循环,其中i循环负责把pos从当前位置累加到n - 1,j循环负责把替换长度从1累加到word.size()-i。
代码如下:

class Solution {
public:
    /**
     * @param word: the given word
     * @return: the generalized abbreviations of a word
     */
    vector<string> generateAbbreviations(string &word) {
        int n = word.size();
        dfs(word, 0);
        result.push_back(word);
        return result;
    }

private:
    vector<string> result;

    void dfs(string word, int pos) {
        int n = word.size();
        if (pos > n) return;
        for (int i = pos; i < n; ++i) {
            for (int j = 1; j <= n - i; ++j) {
                string tmpStr = word.substr(0, i);
                tmpStr += to_string(j) + word.substr(i + j);
                result.push_back(tmpStr);
                dfs(tmpStr, i + to_string(j).size() + 1);
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值