3304. Find the K-th Character in String Game I
Explanation
To solve this problem, we can simulate the process of generating new strings by changing each character to its next character in the English alphabet until the word has at least k characters. We can keep track of the current index in the generated string and update it accordingly. Finally, we return the k-th character in the word.
- We initialize the word as "a" and the current index as 1.
- We iterate from 1 to k, generating new strings by changing each character to its next character and appending it to the original word.
- We update the current index based on the length of the generated string.
- Finally, we return the k-th character in the word.
Time complexity: O(k) Space complexity: O(k)
class Solution {
public char findKthCharacter(int k) {
String word = "a";
int currentIndex = 1;
for (int i = 1; i < k; i++) {
char nextChar = (char)((word.charAt(currentIndex - 1) - 'a' + 1) % 26 + 'a');
word += nextChar;
currentIndex = word.length();
}
return word.charAt(k - 1);
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.