zoukankan      html  css  js  c++  java
  • 0058leetcode算法实现之左翻转字符串reverseLeftStringpython%golang实现 Marathon

    字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"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

    python

    # 坐旋转字符串
    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))
    

    golang

    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)
    }
    
    
  • 相关阅读:
    Linux安装python3.6
    Python安装常见问题(1):zipimport.ZipImportError: can't decompress data
    ModuleNotFoundError: No module named 'apt_pkg'
    【第九届蓝桥杯大赛决赛真题】JAVA大学C组题解
    Mineweep(扫雷)
    Josephus环的四种解法(约瑟夫环)
    java背包的数组实现,链表实现
    Java 实现栈,队列
    java实现单链表
    MySql8最新配置方式(完美)
  • 原文地址:https://www.cnblogs.com/davis12/p/15468839.html
Copyright © 2011-2022 走看看