3744. Find Kth Character in Expanded String π
Description
You are given a string s consisting of one or more words separated by single spaces. Each word in s consists of lowercase English letters.
We obtain the expanded string t from s as follows:
- For each word in
s, repeat its first character once, then its second character twice, and so on.
For example, if s = "hello world", then t = "heelllllllooooo woorrrllllddddd".
You are also given an integer k, representing a valid index of the string t.
Return the kth character of the string t.
Example 1:
Input: s = "hello world", k = 0
Output: "h"
Explanation:
t = "heelllllllooooo woorrrllllddddd". Therefore, the answer is t[0] = "h".
Example 2:
Input: s = "hello world", k = 15
Output: " "
Explanation:
t = "heelllllllooooo woorrrllllddddd". Therefore, the answer is t[15] = " ".
Constraints:
1 <= s.length <= 105scontains only lowercase English letters and spaces' '.sdoes not contain any leading or trailing spaces.- All the words in
sare separated by a single space. 0 <= k < t.length. That is,kis a valid index oft.
Solutions
Solution 1: Math + Simulation
We first split the string \(\textit{s}\) into multiple words by spaces. For each word \(\textit{w}\), we can calculate the length it occupies in the expanded string \(\textit{t}\) as \(m=\frac{(1+|\textit{w}|)\cdot |\textit{w}|}{2}\).
If \(k = m\), it means the \(k\)-th character is a space, and we can directly return a space.
If \(k > m\), it means the \(k\)-th character is not in the expanded part of the current word. We subtract the expanded length \(m\) of the current word and the space length \(1\) from \(k\), and continue processing the next word.
Otherwise, the \(k\)-th character is in the expanded part of the current word. We can find the \(k\)-th character by simulating the expansion process:
- Initialize a variable \(\textit{cur} = 0\) to represent the number of characters that have been expanded so far.
- Iterate through each character \(\textit{w}[i]\) of the word \(\textit{w}\):
- Increase \(\textit{cur}\) by \(i + 1\).
- If \(k < \textit{cur}\), it means the \(k\)-th character is \(\textit{w}[i]\), and we return this character.
The time complexity is \(O(n)\) and the space complexity is \(O(n)\), where \(n\) is the length of the string \(\textit{s}\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
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 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |