题目链接: https://leetcode.com/problems/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 + 回溯. 每一次如果枚举数字化几位, 需要特殊处理的是不数字话, 这种情况是不加0, 其余情况加数字. 然后维护一个索引代表之前的字符都是处理过的, 现在只需要处理后面的字符. 然后有一个bug让我找了很久, 就是字符串超过11位就会出错, 后来发现我只为数字偏移了一位.
代码如下:
class Solution { public: void DFS(string word, int index) { if(index >= word.size()) { result.push_back(word); return; } DFS(word, index+1); for(int i = index; i< word.size(); i++) { int num = word.size()-i; string tem = word.substr(0, index) + to_string(num) + word.substr(index+num); DFS(tem, index + to_string(num).size()+1); } } vector<string> generateAbbreviations(string word) { DFS(word, 0); return result; } private: vector<string> result; };