leetcode344反轉字符串

1.問題描述


編寫一個函數,其作用是將輸入的字符串反轉過來。輸入字符串以字符數組 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"]

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/reverse-string
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

編寫一個函數,其作用是將輸入的字符串反轉過來。輸入字符串以字符數組 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"]

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

2.python求解


我的思路:從頭向中間low++,從尾部向中間high,一起遍歷,low<->high交換。

class Solution(object):
    def reverseString(self, s):
        """
        :type s: List[str]
        :rtype: None Do not return anything, modify s in-place instead.
        """
        low = 0
        high = len(s)-1
        while(low<=high):
            if(low<high):
                temp = s[low]
                s[low] = s[high]
                s[high] = temp
            
            low += 1
            high -= 1

3.知識點補充


 變量交換賦值的寫法

#我的寫法
#以ab交換爲例子
temp = a
a = b
b = temp

#python簡潔寫法
b,a = a,b

#舉個栗子
>>> a,b = 5,6
>>> a,b
(5, 6)
>>> b,a = a,b
>>> a,b
(6, 5)

 

 

 

 

 

 

 

 

 

 

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