当前位置:首页 > IT技术 > 编程语言 > 正文

0344-leetcode算法实现之反转字符串-reverse-string-python&golang实现
2021-10-22 09:57:39

编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。

不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。

示例 1:

输入:s = ["h","e","l","l","o"]
输出:["o","l","l","e","h"]
示例 2:

输入:s = ["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]

提示:

1 <= s.length <= 105
s[i] 都是 ASCII 码表中的可打印字符

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-string

python

# 反转字符串
class Solution:
    def reverseString(self, s: [str]):
        """
        双指针,时间复杂度,O(s),一共进行n/2次元素交换,空间复杂度,常数级变量,O(1)
        思路:
        定义左右指针,初始时指向首尾元素,然后左指针右移++,右指针左移--,直到相遇,即原地反转了字符
        :param s:
        :return:
        """
        if len(s) < 2:
            return s
        right = len(s) -1
        left = 0
        while left < right:
            temp = s[right]
            s[right] = s[left]
            s[left] = temp
            right -= 1
            left += 1

if __name__ == "__main__":
    s = ['s', 'k', 'y', 'i','s']
    s1 = ['s', 'k', 'y', 'i']
    s2 = ['s']
    s3 = []
    test = Solution()
    test.reverseString(s)
    test.reverseString(s1)
    test.reverseString(s2)
    test.reverseString(s3)
    print(s)
    print(s1)
    print(s2)
    print(s3)

golang


func reverseString(s []byte) {
	// 双指针
	if len(s) < 2 {
		return
	}
	left := 0
	right := len(s) - 1

	for left < right {
		temp := s[right]
		s[right] = s[left]
		s[left] = temp
		right--
		left++
	}
}

本文摘自 :https://www.cnblogs.com/

开通会员,享受整站包年服务立即开通 >