Input: k =5Output: "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"`.
The string doubles in size each operation, with the second half being the next character for each in the first half. To find the k-th character, we can “reverse” the process: if k is in the first half, it’s the same as the previous step; if in the second half, it’s the next character of the corresponding position in the first half. This allows us to work backwards recursively until we reach the base case.
classSolution {
public:char findKthCharacter(int k) {
if (k ==1) return'a';
int half =1;
while (half *2< k) half *=2;
char c = findKthCharacter(k <= half ? k : k - half);
if (k <= half) return c;
return c =='z'?'a': c +1;
}
};
classSolution {
publiccharfindKthCharacter(int k) {
if (k == 1) return'a';
int half = 1;
while (half * 2 < k) half *= 2;
char c = findKthCharacter(k <= half ? k : k - half);
if (k <= half) return c;
return c =='z'?'a' : (char)(c + 1);
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
funfindKthCharacter(k: Int): Char {
if (k ==1) return'a'var half = 1while (half * 2 < k) half *=2val c = findKthCharacter(if (k <= half) k else k - half)
if (k <= half) return c
returnif (c =='z') 'a'else c + 1 }
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
deffindKthCharacter(self, k: int) -> str:
if k ==1:
return'a' half =1while half *2< k:
half *=2 c = self.findKthCharacter(k if k <= half else k - half)
if k <= half:
return c
return chr((ord(c) - ord('a') +1) %26+ ord('a'))
impl Solution {
pubfnfind_kth_character(k: i32) -> char {
if k ==1 {
return'a';
}
letmut half =1;
while half *2< k {
half *=2;
}
let c = Solution::find_kth_character(if k <= half { k } else { k - half });
if k <= half {
return c;
}
if c =='z' {
'a' } else {
((c asu8) +1) aschar }
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
findKthCharacter(k: number):string {
if (k===1) return'a';
lethalf=1;
while (half*2<k) half*=2;
constc=this.findKthCharacter(k<=half?k : k-half);
if (k<=half) returnc;
returnc==='z'?'a': String.fromCharCode(c.charCodeAt(0) +1);
}
}