Skip to content

Latest commit

 

History

History
141 lines (102 loc) · 2.89 KB

File metadata and controls

141 lines (102 loc) · 2.89 KB
comments difficulty edit_url
true
简单

题目描述

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

 

示例 1:

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

示例 2:

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

 

限制:

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

解法

方法一:模拟

我们可以将字符串分为两部分,分别对两部分进行翻转,然后再对整个字符串进行翻转,即可得到结果。或者直接截取两个子串,然后拼接起来。

时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串长度。

Python3

class Solution:
    def reverseLeftWords(self, s: str, n: int) -> str:
        return s[n:] + s[:n]

Java

class Solution {
    public String reverseLeftWords(String s, int n) {
        return s.substring(n, s.length()) + s.substring(0, n);
    }
}

C++

class Solution {
public:
    string reverseLeftWords(string s, int n) {
        return s.substr(n) + s.substr(0, n);
    }
};

Go

func reverseLeftWords(s string, n int) string {
	return s[n:] + s[:n]
}

Rust

impl Solution {
    pub fn reverse_left_words(s: String, n: i32) -> String {
        let n = n as usize;
        String::from(&s[n..]) + &s[..n]
    }
}

JavaScript

/**
 * @param {string} s
 * @param {number} n
 * @return {string}
 */
var reverseLeftWords = function (s, n) {
    return s.substring(n) + s.substring(0, n);
};

C#

public class Solution {
    public string ReverseLeftWords(string s, int n) {
        return s.Substring(n) + s.Substring(0, n);
    }
}

Swift

class Solution {
    func reverseLeftWords(_ s: String, _ n: Int) -> String {
        let leftIndex = s.index(s.startIndex, offsetBy: n)
        let rightPart = s[leftIndex..<s.endIndex]
        let leftPart = s[s.startIndex..<leftIndex]
        return String(rightPart) + String(leftPart)
    }
}