-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathDecoded String at Index.cpp
52 lines (38 loc) · 1.25 KB
/
Decoded String at Index.cpp
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
Solution by Rahul Surana
***********************************************************
You are given an encoded string s.
To decode the 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 d, the entire current tape is repeatedly written d - 1 more times in total.
Given an integer k, return the kth letter (1-indexed) in the decoded string.
***********************************************************
*/
#include <bits/stdc++.h>
class Solution {
public:
string decodeAtIndex(string s, int k) {
int i = 0;
long cl = 0;
while(cl < k){
if(isalpha(s[i])){
cl++;
}
else{
cl *= s[i]-'0';
}
i++;
}
for(int j = i-1; j >= 0; j--) {
if(isalpha(s[j])){
if(k == 0 || k == cl) return string(1,s[j]);
cl--;
}
else{
cl /= s[j]-'0';
k%=cl;
}
}
return "";
}
};