Perform String Shifts

Let’s break down the logic into multiple steps and write the Python code accordingly:

  1. Initialize Variables: We’ll initialize a variable to keep track of the total shift, which will be positive for right shifts and negative for left shifts.

  2. Calculate Total Shift: For each shift instruction in the given matrix, we’ll add or subtract the shift amount based on the direction. Right shifts will add to the total shift, and left shifts will subtract.

  3. Normalize the Shift: If the total shift is greater than the length of the string, we need to reduce it using the modulo operation. This way, we handle shifts that are larger than the string’s length.

  4. Perform the Shift: Based on the calculated total shift, we’ll perform the right shift or left shift on the string. This involves taking a slice of the string and rearranging the characters.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
    def stringShift(self, s: str, shift: List[List[int]]) -> str:
        # Step 1: Initialize the total shift variable
        total_shift = 0

        # Step 2: Calculate total shift by iterating through shift instructions
        for direction, amount in shift:
            if direction == 0:
                total_shift -= amount
            else:
                total_shift += amount

        # Step 3: Normalize the total shift by taking modulo of string length
        total_shift = total_shift % len(s)

        # Step 4: Perform the shift based on the total shift
        if total_shift > 0: # Right shift
            s = s[-total_shift:] + s[:-total_shift]
        elif total_shift < 0: # Left shift
            total_shift = abs(total_shift)
            s = s[total_shift:] + s[:total_shift]

        return s

Explanation:

  • The total_shift variable keeps track of the combined shift amount.
  • The loop iterates through the shift matrix, updating total_shift based on the direction.
  • We then normalize total_shift to ensure it is within the bounds of the string length.
  • Finally, we perform the shift by slicing and rearranging the string based on total_shift. If total_shift is zero, the string remains the same.