[Locked] 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"]

分析:

  DFS或者BFS,按照规则将字母替换成数字,注意递归条件和参数的正确性

代码:

void dfs(string &str, vector<string> &vr, string cur, int count, int i) {
    //Condition for ending
    if(i == str.length()) {
        if(count > 0)
            cur += char(count + '0');
        vr.push_back(cur);
        return;
    }
    //Stop converting the characters into numbers
    if(count > 0)
        dfs(str, vr, cur + char(count + '0') + str[i], 0, i + 1);
    else
        dfs(str, vr, cur + str[i], 0, i + 1);
    //Continue converting ....
    dfs(str, vr, cur, count + 1, i + 1);
    return;
}
vector<string> vs(string str) {
    vector<string> vResults;
    dfs(str, vResults, "", 0, 0);
    return vResults;
}

 



posted @ 2016-02-22 23:49  CarlGoodman  阅读(179)  评论(0编辑  收藏  举报