2381. Shifting Letters II #1077
-
Topics: You are given a string Shifting a character forward means replacing it with the next letter in the alphabet (wrapping around so that Return the final string after all such shifts to Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to avoid shifting the characters one by one for each shift, as this would be too slow for large inputs. Instead, we can use a more optimal approach by leveraging a technique called the prefix sum. Steps:
Let's implement this solution in PHP: 2381. Shifting Letters II <?php
/**
* @param String $s
* @param Integer[][] $shifts
* @return String
*/
function shiftingLetters($s, $shifts) {
// Convert the string into an array of characters for easy manipulation
$s = str_split($s);
$n = count($s);
// Create a shift array initialized to zero
$shift = array_fill(0, $n + 1, 0); // One extra element for boundary handling
// Process each shift and mark the beginning and end of the shift
foreach ($shifts as $shiftInfo) {
list($start, $end, $direction) = $shiftInfo;
$shift[$start] += ($direction == 1) ? 1 : -1;
if ($end + 1 < $n) {
$shift[$end + 1] -= ($direction == 1) ? 1 : -1;
}
}
// Apply prefix sum to determine the total shift at each position
$totalShift = 0;
for ($i = 0; $i < $n; $i++) {
$totalShift += $shift[$i];
// Get the new character after shifting
$currentChar = $s[$i];
$shiftedChar = chr(((ord($currentChar) - ord('a') + $totalShift) % 26 + 26) % 26 + ord('a'));
$s[$i] = $shiftedChar;
}
// Convert the array of characters back to a string and return
return implode('', $s);
}
// Test the function
$s1 = "abc";
$shifts1 = [[0, 1, 0], [1, 2, 1], [0, 2, 1]];
echo shiftingLetters($s1, $shifts1) . "\n"; // Output: "ace"
$s2 = "dztz";
$shifts2 = [[0, 0, 0], [1, 1, 1]];
echo shiftingLetters($s2, $shifts2) . "\n"; // Output: "catz"
?> Explanation:
Explanation of Code:
Time Complexity:
This solution efficiently handles the problem even with the upper limits of the input constraints. |
Beta Was this translation helpful? Give feedback.
We need to avoid shifting the characters one by one for each shift, as this would be too slow for large inputs. Instead, we can use a more optimal approach by leveraging a technique called the prefix sum.
Steps: