Iterative bitwise solution


  • 0
    Z

    Using same idea of Subsets. Run time should be O(N * 2 ^ N), N is length of word

     var generateAbbreviations = function(word) {
        var i,j,c;
        var size = word.length;
        var width = 1 << size;
        
        var res = [];
        var ls = [];
        for(i=0;i<width;i++){
            ls = [];
            c = 0;
            for(j=0;j<size;j++){
                if(1 << j & i){
                    if(c !== 0) ls.push(c.toString());
                    c = 0;
                    ls.push(word[j]);
                } else {
                    c++;
                }
            }
            if(c !== 0) ls.push(c);
            res.push(ls.join(''));
        }
        return res;
    };

Log in to reply
 

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