LSGO——LeetCode实战(字符串系列):344题 反转字符串(Reverse String)

原题:

 

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

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

你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。

解法一:

这个就是暴力解法,直接把值往相应的位置insert

class Solution(object):
    def reverseString(self, s):
        """
        :type s: List[str]
        :rtype: None Do not return anything, modify s in-place instead.
        """
        cursor =0
        for i in range(len(s)-1):
            s.insert(cursor,s[-1])
            s.pop()
            cursor += 1

 

解法二:

用python的切片法

class Solution(object):
    def reverseString(self, s):
        """
        :type s: List[str]
        :rtype: None Do not return anything, modify s in-place instead.
        """
        a=s[::-1]
        return a is s

 

解法三:

对半分,相应位置互换。

class Solution(object):
    def reverseString(self, s):
        """
        :type s: List[str]
        :rtype: None Do not return anything, modify s in-place instead.
        """
        for i in range(len(s)//2):
            char = s[i]
            s[i] = s[len(s)-i-1]
            s[len(s)-i-1] = char

最后附上一个对 python变量拷贝讲解的链接,很详细!

https://www.cnblogs.com/Liubit/p/7668476.html

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章