Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

javascript - decodeString codefights: Program doesn't pass all tests."30/31 Output limit exceeded on test -31". Kindly support

function decodeString(s)
{
    let arr = [];
    let digitSum = '';
    let digitSumArr = []; // for numbers before '['
    let i; 

    //iterating string
    for (i = 0; i < s.length; i++)
    {
        if (!isNaN(s[i]))
        {
            digitSum += s[i]; // count number before '['
        }
        else if (s[i] === '[')
        {
            // add number to the array
            digitSumArr.push(+digitSum); 
            arr.push(i + 1);
            digitSum = '';
        }
        else if (s[i] === ']')
        {

            let digit = digitSumArr.pop();
            i = decStr(arr, i, digit);

            digitSum = '';
        }
        else
        {
            digitSum = '';
        }

    }

    return s;

    function decStr(arr, j, number)
    {
        let arrLen = arr.length;
        let n = number;
        let str = s.slice(arr[arrLen - 1], j);
        let sumStr = str;
        while (n-- > 1)
        {
            sumStr = sumStr.concat(str);
        }

        str = number + '[' + str + ']';

        s = s.replace(str, sumStr);

        arr.splice(arrLen - 1, 1);

        //return position for iterating

      return j + sumStr.length - str.length - 1; 
      }
}

Given an encoded string, return its corresponding decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is repeated exactly k times. Note: k is guaranteed to be a positive integer.

Note that your solution should have linear complexity because this is what you will be asked during an interview.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that the failed test has an input of sufficient complexity to require more time to solve than the allotted limit, given your solution. So, you need to find a more efficient solution.

I ran a performance benchmark on your solution and on another solution which used recursive procedure calls, and yours was 33% slower. I suggest you refactor your solution to call your parsing procedure recursively when you encounter nested iterations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...