[LeetCode] Decoded String at Index

880. Decoded String at Index

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
string decodeAtIndex(string S, int K) {
long len = 0;
int i = 0;
for(;len < K; i++) {
if('0' <= S[i] && S[i] <= '9')
len *= (S[i] & 0b1111);
else
++len;
}
i--;
for(; i >= 0; i--) {
K %= len;
if(!K && !('0' <= S[i] && S[i] <= '9'))
return (string)"" + S[i];
if('0' <= S[i] && S[i] <= '9')
len /= (S[i] & 0b1111);
else
--len;
}

return "";
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/23/PS/LeetCode/decoded-string-at-index/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.