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

 

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