【题目】
#示例一
输入:["h","e","l","l","o"]
输出:["o","l","l","e","h"]
#示例二
输入:["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]
【思路】
要求只能O(1)的额外空间。一个算法的空间复杂度为一个常量,即不随被处理数据量n的大小而改变。
关于时间复杂度和空间复杂度–资料
题目很简单,想到的方法是循环length//2次,第一个和最后一个元素进行交换。
【代码】
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
length = len(s)
if length < 2:
return
for i in range(length // 2):
temp = s[i]
s[i] = s[-i-1]
s[-i-1] = temp
【报错】
Do not return anything, modify s in-place instead.
代表不用return任何东西。