3304. Find the K-th Character in String Game I #1882
-
Topics: Alice and Bob are playing a game. Initially, Alice has a string You are given a positive integer Now Bob will ask Alice to perform the following operation forever:
For example, performing the operation on Return the value of the Note that the character Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the k-th character in a string that is constructed by repeatedly performing operations where each character in the current string is replaced by its next character in the alphabet (with 'z' wrapping around to 'a'), and this new string is appended to the original string. The initial string is "a". Approach
This approach efficiently builds the string by simulating each operation step-by-step until the string has at least Let's implement this solution in PHP: 3304. Find the K-th Character in String Game I <?php
/**
* @param Integer $k
* @return String
*/
function kthCharacter($k) {
$s = "a";
while (strlen($s) < $k) {
$t = '';
$len = strlen($s);
for ($i = 0; $i < $len; $i++) {
$c = $s[$i];
if ($c == 'z') {
$t .= 'a';
} else {
$t .= chr(ord($c) + 1);
}
}
$s .= $t;
}
return $s[$k - 1];
}
// Test cases
echo kthCharacter(5); // Output: b
echo "\n";
echo kthCharacter(10); // Output: c
?> Explanation:
This approach efficiently constructs the string by leveraging the operations described, ensuring that the k-th character is found by directly simulating the process until the string is sufficiently long. The solution handles the character wrapping from 'z' to 'a' and efficiently builds the string in logarithmic time relative to |
Beta Was this translation helpful? Give feedback.
We need to find the k-th character in a string that is constructed by repeatedly performing operations where each character in the current string is replaced by its next character in the alphabet (with 'z' wrapping around to 'a'), and this new string is appended to the original string. The initial string is "a".
Approach
k
, perform the following operations: