當前位置:首頁 > IT技術 > 編程語言 > 正文

0344-leetcode算法實現(xiàn)之反轉字符串-reverse-string-python&golang實現(xiàn)
2021-10-22 09:57:39

編寫一個函數(shù),其作用是將輸入的字符串反轉過來。輸入字符串以字符數(shù)組 s 的形式給出。

不要給另外的數(shù)組分配額外的空間,你必須原地修改輸入數(shù)組、使用 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次元素交換,空間復雜度,常數(shù)級變量,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/

開通會員,享受整站包年服務立即開通 >