本问题对应的 leetcode 原文链接:剑指 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) {
        StringBuilder build = new StringBuilder();
        int len = s.length();
        for(int i = n; i < len + n; i++){
            build.append(s.charAt(i%len));
        }

        // for(int i = 0; i < n; i++){
        //     build.append(s.charAt(i));
        // }

        return build.toString();
    }
}

Python

class Solution(object):
    def reverseLeftWords(self, s, n):
        """
        :type s: str
        :type n: int
        :rtype: str
        """
        build = []
        for i in range(n, n+len(s)):
            build.append(s[i%len(s)])
        return ''.join(build)

C++

class Solution {
public:
    string reverseLeftWords(string s, int n) {
        string build;
        for (int i = n; i < n + s.length(); i++) {
            build += s[i % s.length()];
        }
        return build;
    }
};

Go

func reverseLeftWords(s string, n int) string {
    var build strings.Builder
    for i := n; i < n+len(s); i++ {
        build.WriteByte(s[i%len(s)])
    }
    return build.String()
}

JS

/**
 * @param {string} s
 * @param {number} n
 * @return {string}
 */
var reverseLeftWords = function(s, n) {
    let build = [];
    for (let i = n; i < n + s.length; i++) {
        build.push(s.charAt(i % s.length));
    }
    return build.join('');
};

发表回复

后才能评论