Leetcode面试题58 - II. 左旋转字符串

面试题58 - II. 左旋转字符串

难度简单

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

示例 1:

输入: s = "abcdefg", k = 2
输出: "cdefgab"

示例 2:

输入: s = "lrloseumgh", k = 6
输出: "umghlrlose"

限制:

  • 1 <= k < s.length <= 10000

分析:

用切片处理

考虑可能存在n>len(s)这种情况,因此求余

时间复杂度:O(N)

空间复杂度:O(N)

class Solution(object):
    def reverseLeftWords(self, s, n):
        """
        :type s: str
        :type n: int
        :rtype: str
        """
        # 切片处理
        if not s:
            return ""
        n = n % len(s)
        return s[n:] + s[:n]

执行用时 :8 ms, 在所有 Python 提交中击败了99.87%的用户

内存消耗 :13 MB, 在所有 Python 提交中击败了100.00%的用户

猜你喜欢

转载自blog.csdn.net/test121210/article/details/106308479
今日推荐