Recursive JS (JavaScript) solution


  • 0
    W

    This solution felt naturally recursive to me. Of course seeing other solutions in the discussion, a stack also makes a lot of sense :) I think stack is possibly even more time efficient at the cost of space.

    var decodeString = function(s) {
        let str = "";
        let num = 0;
        let ss = "";
        let opened = 0;
        for (let i = 0; i < s.length; i++) {
            let chr = s.substr(i, 1);
            if (opened >= 1) ss += chr;
            if (chr == "[") opened++;
            else if (chr == "]") {
                opened--;
                if (opened == 0) {
                    for (let j = 0; j < num; j++) {
                        str += decodeString(ss);
                    }
                    num = 0;
                    ss = "";
                }
            } else {
                if (opened == 0) {
                    if (chr >= 0 || chr <= 9) num = `${num}${chr}`;
                    else str += chr;
                }
            }
        }
        return str;
    };
    

Log in to reply
 

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