One traverse js solution


  • 1
    C
    var magicalString = function(n) {
        if (!n) return n;
        var sb = [1, 2, 2];
        var count = 1;
        for (var i = 3; i <= n; i++) {
            if (sb[i - 1] === 1) count++;
            for (var j = 0; j < sb[i - 1]; j++) sb.push((i % 2) ? 1 : 2);
        }
        return count;
    };
    

Log in to reply
 

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