1790. 旋转字符串II

1790. 旋转字符串II

中文English

给出一个字符串(以字符数组形式给出),一个右偏移和一个左偏移,根据给出的偏移量循环移动字符串。(left offest表示字符串向左的偏移量,right offest表示字符串向右的偏移量,左偏移量和右偏移量计算得到总偏移量,在总偏移量处分成两段字符串并交换位置)。

样例

Example 1:

Input:str ="abcdefg", left = 3, right = 1
Output:"cdefgab"
Explanation:The left offset is 3, the right offset is 1, and the total offset is left 2. Therefore, the original string moves to the left and becomes "cdefg"+ "ab".

Example 2:

Input:str="abcdefg", left = 0, right = 0
Output:"abcdefg"
Explanation:The left offset is 0, the right offset is 0, and the total offset is 0. So the string remains unchanged.

Example 3:

Input:str = "abcdefg",left = 1, right = 2
Output:"gabcdef"
Explanation:The left offset is 1, the right offset is 2, and the total offset is right 1. Therefore, the original string moves to the left and becomes "g" + "abcdef".

class Solution:
    """
    @param str: A String
    @param left: a left offset
    @param right: a right offset
    @return: return a rotate string
    """
    def RotateString2(self, str, left, right):
        # write your code here
        length = len(str)
        
        if left == right:
            return str
        elif left > right:
            left_offset = (left - right) % length
            return str[left_offset: ] + str[: left_offset]
        else:
            right_offset = (right - left ) % length
            return str[length - right_offset: ] + str[: length - right_offset]
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/14131330.html