您的位置:首页 > 其它

320. Generalized Abbreviation

2016-03-14 13:41 453 查看

Problem

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




Solution 

典型的 backtracking, 唯一要注意的是例子给的单词长度是各位数,要考虑单词很长的时候可以是两位数,这样就不能用  num + '0' 来表示当前的数字字符了。

class Solution {
void helper(int begin, string& oneRst, vector<string>& rst, const string& word ){

if(begin == word.size()) {
rst.push_back(oneRst);
return;
}

oneRst.push_back(word[begin]);
helper(begin + 1, oneRst, rst, word);
oneRst.pop_back();

if( oneRst.empty() ||  oneRst.back() < '0' || oneRst.back() > '9' ){
for( int numLen = 1; numLen <= word.size() - begin; numLen++) {
string str = to_string(numLen);
oneRst.append(str);
helper(begin + numLen, oneRst, rst, word);
oneRst.erase(oneRst.end() - str.size(), oneRst.end());
}
}
}

public:
vector<string> generateAbbreviations(string word) {
string oneRst;
vector<string> rst;
helper(0, oneRst, rst, word);
return rst;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  back tracking