You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction_i, amount_i]:
direction_i can be 0 (for left shift) or 1 (for right shift).amount_i is the amount by which string s is to be shifted.s and append it to the end.s and add it to the beginning.Return the final string after all operations.
Example 1:
Input: s = "abc", shift = [[0,1],[1,2]]
Output: "cab"Explanation:
[0,1] means shift to left by 1. "abc" -> "bca"
[1,2] means shift to right by 2. "bca" -> "cab"
Example 2:
Input: s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]]
Output: "efgabcd"Explanation:
[1,1] means shift to right by 1. "abcdefg" -> "gabcdef"
[1,1] means shift to right by 1. "gabcdef" -> "fgabcde"
[0,2] means shift to left by 2. "fgabcde" -> "abcdefg"
[1,3] means shift to right by 3. "abcdefg" -> "efgabcd"
Constraints:
1 <= s.length <= 100s only contains lower case English letters.1 <= shift.length <= 100shift[i].length == 2direction_i is either 0 or 1.0 <= amount_i <= 100class Solution:
def stringShift(self, s: str, shift: List[List[int]]) -> str:
for direction, amount in shift:
amount %= len(s)
if direction == 0:
# Move necessary amount of characters from start to end
s = s[amount:] + s[:amount]
else:
# Move necessary amount of characters from end to start
s = s[-amount:] + s[:-amount]
return sWhere is the length of the string and is the length of the
shiftarray
class Solution:
def stringShift(self, s: str, shift: List[List[int]]) -> str:
# Count the number of left shifts. A right shift is a negative left shift.
left_shifts = 0
for direction, amount in shift:
if direction == 1:
amount = -amount
left_shifts += amount
# Convert back to a positive, do left shifts, and return.
left_shifts %= len(s)
s = s[left_shifts:] + s[:left_shifts]
return sWhere is the length of the string and is the length of the
shiftarray