Another C++ bit manipulation based solution


  • 1
    class Solution {
    public:
        vector<string> generateAbbreviations(string word) {
            vector<string> ret;
            int size = word.size();
            int set_size = pow(2, size);
            for (int i = 0; i < set_size; ++i) {
                string str; int count = 0;
                for (int j = 0; j < size; ++j) {
                    if ((i >> j) & 1) {
                        if (count) {
                            str += to_string(count);
                            count = 0;
                        }
                        str += word[j];
                    } else {
                        ++count;
                    }
                }
                if (count) {
                    str += to_string(count);
                }
                ret.emplace_back(str);
            }
            return ret;
        }
    };
    

    Inspired by https://leetcode.com/discuss/9213/my-solution-using-bit-manipulation


Log in to reply
 

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