|
| 1 | +# 880. Decoded String at Index |
| 2 | +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: |
| 3 | + |
| 4 | +* If the character read is a letter, that letter is written onto the tape. |
| 5 | +* If the character read is a digit `d`, the entire current tape is repeatedly written `d - 1` more times in total. |
| 6 | + |
| 7 | +Given an integer `k`, return *the* <code>k<sup>th</sup></code> *letter (**1-indexed**) in the decoded string*. |
| 8 | + |
| 9 | +#### Example 1: |
| 10 | +<pre> |
| 11 | +<strong>Input:</strong> s = "leet2code3", k = 10 |
| 12 | +<strong>Output:</strong> "o" |
| 13 | +<strong>Explanation:</strong> The decoded string is "leetleetcodeleetleetcodeleetleetcode". |
| 14 | +The 10th letter in the string is "o". |
| 15 | +</pre> |
| 16 | + |
| 17 | +#### Example 2: |
| 18 | +<pre> |
| 19 | +<strong>Input:</strong> s = "ha22", k = 5 |
| 20 | +<strong>Output:</strong> "h" |
| 21 | +<strong>Explanation:</strong> The decoded string is "hahahaha". |
| 22 | +The 5th letter is "h". |
| 23 | +</pre> |
| 24 | + |
| 25 | +#### Example 3: |
| 26 | +<pre> |
| 27 | +<strong>Input:</strong> s = "a2345678999999999999999", k = 1 |
| 28 | +<strong>Output:</strong> "a" |
| 29 | +<strong>Explanation:</strong> The decoded string is "a" repeated 8301530446056247680 times. |
| 30 | +The 1st letter is "a". |
| 31 | +</pre> |
| 32 | + |
| 33 | +#### Constraints: |
| 34 | +* `2 <= s.length <= 100` |
| 35 | +* `s` consists of lowercase English letters and digits `2` through `9`. |
| 36 | +* `s` starts with a letter. |
| 37 | +* <code>1 <= k <= 10<sup>9</sup></code> |
| 38 | +* It is guaranteed that `k` is less than or equal to the length of the decoded string. |
| 39 | +* The decoded string is guaranteed to have less than <code>2<sup>63</sup></code> letters. |
| 40 | + |
| 41 | +## Solutions (Rust) |
| 42 | + |
| 43 | +### 1. Solution |
| 44 | +```Rust |
| 45 | +impl Solution { |
| 46 | + pub fn decode_at_index(s: String, k: i32) -> String { |
| 47 | + let mut k = k as i64 - 1; |
| 48 | + let mut chars = vec![]; |
| 49 | + let mut length = 0; |
| 50 | + |
| 51 | + for ch in s.bytes() { |
| 52 | + chars.push((ch, length)); |
| 53 | + |
| 54 | + if ch.is_ascii_lowercase() { |
| 55 | + length += 1; |
| 56 | + } else { |
| 57 | + length *= (ch - b'0') as i64; |
| 58 | + } |
| 59 | + |
| 60 | + if length > k { |
| 61 | + break; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + while let Some((ch, i)) = chars.pop() { |
| 66 | + if ch.is_ascii_lowercase() { |
| 67 | + if i == k { |
| 68 | + return String::from_utf8(vec![ch]).unwrap(); |
| 69 | + } |
| 70 | + |
| 71 | + length -= 1; |
| 72 | + } else { |
| 73 | + length /= (ch - b'0') as i64; |
| 74 | + k %= length; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + unreachable!() |
| 79 | + } |
| 80 | +} |
| 81 | +``` |
0 commit comments