字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
示例 1:
输入: s = "abcdefg", k = 2
输出: "cdefgab"
示例 2:
输入: s = "lrloseumgh", k = 6
输出: "umghlrlose"
限制:
1 <= k < s.length <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof
# 坐旋转字符串 class Solution: def reverseLeftString1(self, s: str, k: int) -> str: """ 字符串切片拼接 时间/空间O(n),效率高 :param s: :param k: :return: """ return s[k:] + s[:k] def reverseLeftString2(self, s, k): """ 列表遍历拼接,申请一次内存 :param s: :param k: :return: """ res = [] n = len(s) for i in range(k, n): res.append(s[i]) for i in range(0, k): res.append(s[i]) return ''.join(res) def reverseLeftString3(self, s, k): """ 字符串遍历拼接,与上类似, 申请n次内存,效率低 :param s: :param k: :return: """ res = "" n = len(s) for i in range(k, n): res += s[i] for i in range(0, k): res += s[i] return res if __name__ == "__main__": s = "skyisblue" k = 3 test = Solution() print(test.reverseLeftString1(s,k)) print(test.reverseLeftString2(s,k)) print(test.reverseLeftString3(s,k))
package main import "fmt" func main() { s := "skyisblue" fmt.Println(reverseLeftString3(s, 3)) } // 字符串切片拼接 func reverseLeftString3(s string, k int) string { return string(s[k:]) + string(s[:k]) } // 字符拼接 func reverseLeftString2(s string, k int) string { res := "" for i := k; i < len(s); i++ { res = res + string(s[i]) } for i := 0; i < k; i++ { res = res + string(s[i]) } return res } // 切片拼接 func reverseLeftString1(s string, k int) string { res_array := []byte{} for i := k; i < len(s); i++ { res_array = append(res_array, s[i]) } for i := 0; i < k; i++ { res_array = append(res_array, s[i]) } return string(res_array) }