简体   繁体   中英

880. Decoded String at Index (LeetCode)

An encoded string S is given. To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken:

If the character read is a letter, that letter is written onto the tape. If the character read is a digit (say d), the entire current tape is repeatedly written d-1 more times in total. Now for some encoded string S, and an index K, find and return the K-th letter (1 indexed) in the decoded string.

Attached my solution it is shows different O/P for this input, can any one please suggest me what needs to be changes in m solution. thanks in advance.

INPUT decodeAtIndex ("vzpp636m8y", 2920) Expected O/p = "z" The Output I got = "p"


var decodeAtIndex = function(S, K) {
    let res = '';
    let hasNumber = false;
    let number = '';
    let i = 0;
    
    while((i < S.length)) {
          if(S[i] < 10) {
              number = number + S[i];
              hasNumber = true;
              while(S[i + 1] < 10) {
                    number = number + S[++i];
              }
          }
        
        if (hasNumber) {
           let repeat = res.repeat(parseInt(number - 1));
            res = `${res}${repeat}`; 
            hasNumber = false;
            number = '';
        } else {
            res = `${res}${S[i]}`;            
        }
        i++;
    }    
    return res[K - 1];
    
};

Your code is fine (short of this typo parseInt(number - 1) , where you're subtracting before parsing).

However you understood the problem wrong. It's explicitly state that if a digit d is encountered, repeat the tape up to that point another d - 1 times. Not number, mind you. Ie a222 doesn't translate to

repeat('a', 222)

but

repeat(repeat(repeat('a', 2), 2), 2) = repeat('a', 8)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM