Clean C++ solution with some ADVICE


  • 0
    2

    At first, I use the the following condition to call the dfs function like this :

    dfs(result, pos + 1, 0, size, word, cur + (skip == 0 ? cur + word[i] : cur + to_string(skip) + word[i])
    

    This is not a good coding style to write the code like this, we should not embed the condition check into the parameters of the function calling.

    So here is a more readable version , when we write the code , the readability is the most important !

    class Solution {
    public:
        vector<string> generateAbbreviations(string word) {
            vector<string> result;
            dfs(result, 0, 0, word.size(), word, "");
            return result;
        }
        
        void dfs(vector<string>& result, int pos, int skip, const int& size, const string& word, string cur) {
            if(pos == size) {
                if(skip != 0)
                    cur += to_string(skip);
                result.push_back(cur);
                return;
            }
            if(skip == 0){
                dfs(result, pos + 1, skip, size, word, cur + word[pos]);
                dfs(result, pos + 1, skip + 1, size, word, cur);
            }
            else {
                dfs(result, pos + 1, 0, size, word, cur + to_string(skip) + word[pos]);
                dfs(result, pos + 1, skip + 1, size, word, cur);
            }
        }
    };

Log in to reply
 

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