剑指 Offer 58 – II. 左旋转字符串

一、题目描述

字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。

请定义一个函数实现字符串左旋转操作的功能。

比如,输入字符串”abcdefg”和数字2,该函数将返回左旋转两位得到的结果”cdefgab”。

示例 1:

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

示例 2:

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

限制:

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

二、题目解析

为了帮助你更好的理解整个过程,我特意做了一组动画,点开可以查看

三、参考代码

class Solution {
    public String reverseLeftWords(String s, int n) {
        // 1、获取字符串的长度
        int length = s.length();
        // 2、把字符串转换为字符数组的形式
        char[] chars = s.toCharArray();

        // 3、把字符数组的所有字符反转
        // 即  a b c d e f g 
        // 变成了 g f e d c b a
        reverse(chars, 0, length - 1);

        // 4、再反转前 length - n 个字符
        // 即  g f e d c b a
        // 变成了 c d e f g b a
        reverse(chars, 0, length - n - 1);

        // 5、再反转剩余的字符   
        // 即  c d e f g b a
        // 变成了 c d e f g a b
        reverse(chars, length - n, length - 1);

        // 6、最后返回字符串结果就可以
        return new String(chars);
    }

    // 借助临时变量的方法,把字符数组进行反转
    private void reverse(char[] chars, int start, int end) {
        // 从头到尾变量所有的字符
        while (start < end) {
            // 定义一个临时变量用来保存字符数组的开始字符
            char temp = chars[start];

            // 将首尾字符交换
            chars[start] = chars[end];

            // 将首尾字符交换
            chars[end] = temp;

            start++;
            end--;
        }
    }

}

2、C++ 代码

class Solution {
public:
    string reverseLeftWords(string s, int n) {

        int length = s.size();

        // 1、把字符数组的所有字符反转
        // 即  a b c d e f g 
        // 变成了 g f e d c b a
        reverse(s.begin(),s.end());

        // 2、再反转前 length - n 个字符
        // 即  g f e d c b a
        // 变成了 c d e f g b a
        reverse(s.begin(),s.begin() + length - n  );

        // 2、再反转剩余的字符   
        // 即  c d e f g b a
        // 变成了 c d e f g a b
        reverse(s.begin() + length - n  ,s.end());

        // 3、最后返回字符串结果就可以
        return s;
    }
};

3、Python 代码

class Solution:
    def reverseLeftWords(self, s: str, n: int) -> str:

        res = list(s)

        # 1、把字符数组的所有字符反转
        # 即  a b c d e f g 
        # 变成了 g f e d c b a
        self.reverse( res , 0 , len(s) - 1 )

        # 2、再反转前 length - n 个字符
        # 即  g f e d c b a
        # 变成了 c d e f g b a
        self.reverse(res , 0 , len(s) - n - 1)

        # 3、再反转剩余的字符   
        # 即  c d e f g b a
        # 变成了 c d e f g a b
        self.reverse( res , len(s) - n   , len(s) - 1 )


        return "".join(res)

    def reverse(self,res,start, end):
        while start < end:
            res[start], res[end] = res[end], res[start]
            start += 1
            end -= 1