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

 

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