天天看點

LeetCode 344. 反轉字元串

題目

編寫一個函數,其作用是将輸入的字元串反轉過來。輸入字元串以字元數組 char[] 的形式給出。

不要給另外的數組配置設定額外的空間,你必須原地修改輸入數組、使用 O(1) 的額外空間解決這一問題。

你可以假設數組中的所有字元都是 ASCII 碼表中的可列印字元。

示例 1:

輸入:["h","e","l","l","o"]
輸出:["o","l","l","e","h"]
示例 2:

輸入:["H","a","n","n","a","h"]
輸出:["h","a","n","n","a","H"]           

解題思路

class Solution:
    def reverseString(self, s: [str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        #交叉替換
        # midNum = len(s)//2
        # for i in range(midNum):
        #     s[i], s[len(s)-1-i] = s[len(s)-1-i], s[i]
        #python内置函數
        s.reverse()