LeetCode 1427: Perform String Shifts

ArrayMathString

Problem Description

Explanation:

The problem requires us to perform string shifts on a given string based on a set of shift operations. Each shift operation consists of a direction (0 for left shift, 1 for right shift) and an amount of shift. We need to apply these operations sequentially and return the final string after all shifts are performed.

To solve this problem, we can calculate the total shift amount by summing up all the shift amounts in the given operations. We can then perform the actual shift operation based on the total shift amount modulo the length of the string to handle wrap-around shifts.

Here is the step-by-step algorithm:

  1. Calculate the total shift amount by summing up all the shift amounts in the given operations.
  2. Adjust the total shift amount to ensure it is within the length of the string by taking the modulo operation with the length of the string.
  3. Perform the shift operation based on the adjusted total shift amount: if it is positive, perform a right shift; if it is negative, perform a left shift.
  4. Return the final shifted string.

Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(1).

:

Solutions

class Solution {
    public String stringShift(String s, int[][] shift) {
        int totalShift = 0;
        for (int[] sh : shift) {
            totalShift += sh[0] == 0 ? -sh[1] : sh[1];
        }
        
        totalShift %= s.length();
        if (totalShift < 0) {
            totalShift += s.length();
        }
        
        return s.substring(s.length() - totalShift) + s.substring(0, s.length() - totalShift);
    }
}

Loading editor...