Javascript solution with stack


  • 0
    X

    Javascript solution with stack

    var decodeString = function(s) {
        var stack = [];
        var i=0;
        var j=0;
        for(; i<s.length; i++) {
            var buf = [];
            var seq;
            var freq = 0;
            var c = s.charAt(i);
            if (c===']') {
                for(j = stack.length-1; j>=0; j--) {
                    var p = stack.pop();
                    if (p === '[') {
                        seq = buf.join('');
                        buf = [];
                        for(var k=j-1; k>=0 && stack[k]>='0' && stack[k]<='9'; k--) {
                            buf.unshift(stack.pop());
                        }
                        freq=parseInt(buf.join(''));
                        stack.push(Array(freq+1).join(seq));
                        buf = [];
                        break;
                    }
                    else {
                        buf.unshift(p);
                    }
                }
            }
            else {
                stack.push(c);
            }
        }
        return stack.join('');
    };

Log in to reply
 

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