反轉字符串,原地工作,其實就是第一個元素與倒數第一個元素交換,倒數第二個元素與倒數第二個元素交換。得到字符串中間元素的下表,偶數個和奇數個均適用。然後從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