Skip to content

Commit 564791a

Browse files
authored
Create decoded-string-at-index.cpp
1 parent 88c2dd1 commit 564791a

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

C++/decoded-string-at-index.cpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
string decodeAtIndex(string S, int K) {
7+
uint64_t n = 0;
8+
for (int i = 0; i < S.length(); ++i) {
9+
if (isdigit(S[i])) {
10+
n *= S[i] - '0';
11+
} else {
12+
++n;
13+
}
14+
}
15+
16+
for (int i = S.length() - 1; i >= 0; --i) {
17+
K %= n;
18+
if (K == 0 && isalpha(S[i])) {
19+
return (string) "" + S[i];
20+
}
21+
22+
if (isdigit(S[i])) {
23+
n /= S[i] - '0';
24+
} else {
25+
--n;
26+
}
27+
}
28+
}
29+
};

0 commit comments

Comments
 (0)