Leetcode 880. Decoded String at Index
Leetcode Problem 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:
d
), the entire current tape is repeatedly written d-1
more times in total.Given an encoded string S
and an index K
, find and return the K
-th letter (1-indexed) in the decoded string.
S
?
K
be larger than the possible length of the decoded string?
K
is always valid, it simplifies the problem as we don’t need to handle out-of-bounds cases.S
contain?
S
contains only lowercase letters and digits.Assuming typical constraints:
S
can be up to 100 characters.K
is always valid and within the bounds of the decoded string length.S
contains only lowercase letters and digits.S
to find the position of the K-th character.#include <string>
using namespace std;
class Solution {
public:
string decodeAtIndex(string S, int K) {
long long size = 0; // Long long to handle large sizes
// Step 1: Calculate the size of the final decoded string.
for (char c : S) {
if (isdigit(c)) {
size *= (c - '0');
} else {
size++;
}
}
// Step 2: Work backwards to find the K-th character.
for (int i = S.size() - 1; i >= 0; --i) {
K %= size;
if (K == 0 && isalpha(S[i])) {
return string(1, S[i]);
}
if (isdigit(S[i])) {
size /= (S[i] - '0');
} else {
size--;
}
}
return ""; // Should not be reached
}
};
Time Complexity: O(N)
Space Complexity: O(1)
This approach efficiently determines the K-th character in the decoded string without explicitly constructing the entire decoded string, making it suitable for large values of K
and large decoded strings.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?