[LeetCode] Find the K-th Character in String Game I

3304. Find the K-th Character in String Game I

Alice and Bob are playing a game. Initially, Alice has a string word = "a".

You are given a positive integer k.

Now Bob will ask Alice to perform the following operation forever:

  • Generate a new string by changing each character in word to its next character in the English alphabet, and append it to the original word.

For example, performing the operation on "c" generates "cd" and performing the operation on "zb" generates "zbac".

Return the value of the kth character in word, after enough operations have been done for word to have at least k characters.

Note that the character 'z' can be changed to 'a' in the operation.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
char kthCharacter(long long k) {
string s = "a";
int pos = 0;
while(s.length() <= k) {
string ss = s;
for(auto& ch : ss) ch++;
s = s + ss;
}
return s[k-1];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/09/29/PS/LeetCode/find-the-k-th-character-in-string-game-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.