测试面试LeetCode系列:字符串的左旋转

题目

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

示例 1:ide

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

示例 2:post

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


限制:.net

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

来源:LeetCode(力扣)blog


思路

1. 若是是python的话,能够直接对字符串进行切片,而后对切片后的字符串进行拼接。字符串

2. 遍历字符串,在将k以前的字符串保存一份为a,将k以后的字符串再保存一份b,返回b+a便可。get

实现

#解法1
class Solution(object):

    def reverseLeftWords(self, s, n):
        """
        :type s: str
        :type n: int
        :rtype: str
        """
        pre_str = s[:n]
        post_str = s[n:]
        return post_str+pre_str

#解法2
class Solution(object):
    def reverseLeftWords(self, s, n):
        """
        :type s: str
        :type n: int
        :rtype: str
        """
        pre_str = ""
        post_str = ""
        for index,ch in enumerate(s):
            if index < n:
                post_str = post_str + ch
            else:
                pre_str = pre_str + ch
        return pre_str+post_str

各位大神,有其余思路欢迎留言~博客

博主:测试生财

座右铭:专一测试与自动化,致力提升研发效能;经过测试精进完成原始积累,经过读书理财奔向财务自由。

csdn:https://blog.csdn.net/ccgshigao

博客园:https://www.cnblogs.com/qa-freeroad/

51cto:https://blog.51cto.com/14900374

相关文章
相关标签/搜索