C++ straightforward recursive solution


  • 5
    J
    void generateAbbreviations(vector<string>& result, string word, int pos) {
    	for (int i = pos; i<word.length(); i++) {
    		for (int j = 1; i + j<=word.length(); j++) {
    			string t = word.substr(0, i);
    			t += to_string(j) + word.substr(i + j);
    			result.push_back(t);
    			generateAbbreviations(result, t, i + 1 + to_string(j).length());
    		}
    	}
    }
    
    vector<string> generateAbbreviations(string word) {
    	vector<string> result;
    	result.push_back(word);
    	generateAbbreviations(result, word, 0);
    	return result;
    }

  • 0
    Z

    You could use word.replace(i, j, to_string(j)); which is faster, I think


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.