โ† All problems

3304. Find the K Th Character in String Game I

EasyOpen on LeetCodeProblem statement

Problem Statement

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

Easy


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:

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:

Example 2:

Input: k = 10

Output: "c"

 

Constraints:

Java โ€” simulation

Source file
class Solution {
    public char kthCharacter(int k) {
        StringBuilder sb = new StringBuilder("a");
        int len = 1;
        while (len < k) {
            for (int i = 0; i < len; i++)
                sb.append((char) (((sb.charAt(i) - 'a' + 1) % 26) + 'a'));
            len = sb.length();
        }
        System.out.println(sb);
        return sb.charAt(k - 1);
    }
}