Problem
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 writtend - 1
more times in total.
Given an integer k
, return the kth
letter (1-indexed) in the decoded string.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Decode the string
To decode the string and return the kth
letter, we can follow these key steps:
- Calculate the Total Length of the Decoded String:
- Iterate through the encoded string to calculate the length of the decoded string. During this:
- If a character is a digit, multiply the current length by this digit.
- If a character is a letter, increment the length by one.
- Iterate through the encoded string to calculate the length of the decoded string. During this:
- Determine the
kth
letter:- Traverse the string in reverse (from the end to the beginning).
- Update
k
to bek % len
to account for possible repetitions. - If a character is a digit, divide the current length by this digit.
- If a character is a letter and
k
is 0 (after the modulo operation), this character is thekth
letter.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the input strings
.- First, we iterate through the string to calculate the total length.
- Then, we iterate through the string again to determine the
kth
letter.
- 🧺 Space complexity:
O(1)
, since we use only a few variables to store the current length, index, and the modulo result.