Skip to content

Latest commit

 

History

History
42 lines (30 loc) · 1.08 KB

面试题58-2.md

File metadata and controls

42 lines (30 loc) · 1.08 KB

题目描述

  • 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部
  • 请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。

解法1:字符串切片

  • 时间复杂度和空间复杂度为O(N)
class Solution:
    def reverseLeftWords(self, s: str, n: int) -> str:
        return s[n:] + s[:n]

解法2:列表遍历拼接

  • 时间复杂度和空间复杂度为O(N)
class Solution:
    def reverseLeftWords(self, s: str, n: int) -> str:
        return s[n:] + s[:n]

解法3:字符串拼接

  • 时间复杂度和空间复杂度为O(N)
class Solution:
    def reverseLeftWords(self, s: str, n: int) -> str:
        res = ""
        for i in range(n, len(s)):
            res += s[i]
        for i in range(n):
            res += s[i]
        return res