Rotate String II – Python 3 (Week 13 – 12)

Solution 1

class Solution:
    """
    @param str: An array of char
    @param left: a left offset
    @param right: a right offset
    @return: return a rotate string
    """
    def RotateString2(self, s, left, right):
        # write your code here
        if not s:
            return ''
        result = ''
        
        n = len(s)
        offset = (left - right) % n
        #if left - right < 0:  right offset x
        #x % n = (x % n) + n in python
        result = s[offset : ] + s[ : offset]
    
        return result

Time O(n). Space O(n).

Leave a comment

Design a site like this with WordPress.com
Get started