leedcode 反轉字符串

反轉字符串,原地工作,其實就是第一個元素與倒數第一個元素交換,倒數第二個元素與倒數第二個元素交換。得到字符串中間元素的下表,偶數個和奇數個均適用。然後從0循環到中間元素的下標,i需要交換的下標爲len_s - i - 1.

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

 

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