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

3307. Find the K-th Character in String Game II

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

You are given a positive integer k. You are also given an integer array operations, where operations[i] represents the type of the ith operation.

Now Bob will ask Alice to perform all operations in sequence:

  • If operations[i] == 0, append a copy of word to itself.
  • If operations[i] == 1, 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 performing all the operations.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main

func helper(op []int, pos int64, k *int64) int {
len := int64(1) << pos
if len >= *k {
return 0
}
res := helper(op, pos+1, k)
if len < *k {
*k -= len
res = (res + op[pos]) % 26
}
return res
}

func kthCharacter(k int64, operations []int) byte {
return byte('a' + helper(operations, 0, &k))
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/09/29/PS/LeetCode/find-the-k-th-character-in-string-game-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.