2381. Shifting Letters II
Difficulty: Medium
Topics: Array, String, Prefix Sum
You are given a string s of lowercase English letters and a 2D integer array shifts where shifts[i] = [starti, endi, directioni]. For every i, shift the characters in s from the index starti to the index endi (inclusive) forward if directioni = 1, or shift the characters backward if directioni = 0.
Shifting a character forward means replacing it with the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Similarly, shifting a character backward means replacing it with the previous letter in the alphabet (wrapping around so that 'a' becomes 'z').
Return the final string after all such shifts to s are applied.
Example 1:
Example 2:
Constraints:
Hint:
Solution:
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.
Let's implement this solution in PHP: 2381. Shifting Letters II
Explanation:
- For each shift [start, end, direction], we'll increment a shift array at start and decrement at end 1. This allows us to track the start and end of the shift range.
- After processing all the shifts, we apply a prefix sum on the shift array to get the cumulative shift at each index.
- Finally, we apply the cumulative shift to each character in the string.
Explanation of Code:
- Input Parsing: We convert the input string s into an array of characters for easier manipulation.
- Shift Array: We initialize a shift array of size n 1 to zero. This array is used to track the shift effects. For each shift [start, end, direction], we adjust the values at shift[start] and shift[end 1] to reflect the start and end of the shift.
- Prefix Sum: We calculate the total shift for each character by iterating over the shift array and maintaining a cumulative sum of shifts.
- Character Shifting: For each character in the string, we compute the final shifted character using the formula (ord(currentChar) - ord('a') totalShift) % 26, which accounts for the circular nature of the alphabet.
- Return Result: The final string is obtained by converting the character array back into a string and returning it.
Time Complexity:
This solution efficiently handles the problem even with the upper limits of the input constraints.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Shifting Letters II. For more information, please follow other related articles on the PHP Chinese website!