comments | difficulty | edit_url | rating | source | tags | ||||
---|---|---|---|---|---|---|---|---|---|
true |
Easy |
1288 |
Weekly Contest 417 Q1 |
|
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 originalword
.
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.
Example 1:
Input: k = 5
Output: "b"
Explanation:
Initially, word = "a"
. We need to do the operation three times:
- Generated string is
"b"
,word
becomes"ab"
. - Generated string is
"bc"
,word
becomes"abbc"
. - Generated string is
"bccd"
,word
becomes"abbcbccd"
.
Example 2:
Input: k = 10
Output: "c"
Constraints:
1 <= k <= 500
We can use an array
Finally, return
The time complexity is
class Solution:
def kthCharacter(self, k: int) -> str:
word = [0]
while len(word) < k:
word.extend([(x + 1) % 26 for x in word])
return chr(ord("a") + word[k - 1])
class Solution {
public char kthCharacter(int k) {
List<Integer> word = new ArrayList<>();
word.add(0);
while (word.size() < k) {
for (int i = 0, m = word.size(); i < m; ++i) {
word.add((word.get(i) + 1) % 26);
}
}
return (char) ('a' + word.get(k - 1));
}
}
class Solution {
public:
char kthCharacter(int k) {
vector<int> word;
word.push_back(0);
while (word.size() < k) {
int m = word.size();
for (int i = 0; i < m; ++i) {
word.push_back((word[i] + 1) % 26);
}
}
return 'a' + word[k - 1];
}
};
func kthCharacter(k int) byte {
word := []int{0}
for len(word) < k {
m := len(word)
for i := 0; i < m; i++ {
word = append(word, (word[i]+1)%26)
}
}
return 'a' + byte(word[k-1])
}
function kthCharacter(k: number): string {
const word: number[] = [0];
while (word.length < k) {
word.push(...word.map(x => (x + 1) % 26));
}
return String.fromCharCode(97 + word[k - 1]);
}