Other algorithms -043- string left rotation

Article Directory

Title Description

There is a shift in the assembly language instruction called a rotate left (the ROL), and now there is a simple task, this instruction is simulated by the string operation result. For a given character sequence S, you put its left circle after K-bit serial output. For example, the character sequence S = "abcXYZdef", rotated left required output result after three, i.e. "XYZdefabc". Is not it simple? OK, get it!

analysis

  • A method of moving. The former l e n g t h % n length\%n number of moves behind. Time complexity of O (n), the spatial complexity is O (1).
  • Method Two: inversion. A whole string inversion ago l e n g t h l e n g t h % n length-length\%n string inversion, after l e n g t h % n length\%n inversion.

Code

# -*- coding:utf-8 -*-
class Solution:
    def LeftRotateString(self, s, n):
        # write code here
        
        if not s:
            return ''
        
        ROL = n%len(s)
        return s[ROL:]+s[:ROL]
Published 219 original articles · won praise 85 · Views 140,000 +

Guess you like

Origin blog.csdn.net/z_feng12489/article/details/103599927