题目:
Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.
给定一个由字元组成的阵列,将其反转
题目限制我们的空间複杂度只能是O(1)
这题用简单的two pointer就能解决
class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ l=0 r=len(s)-1 while l<r: temp=s[l] s[l]=s[r] s[r]=temp l=l+1 r=r-1
设立两个指标(l,r),一个从阵列头,一个从阵列尾开始走
路上不断交换值直到两者相遇或交错
我们就成功反转该阵列了
最后执行时间197ms(faster than 98.06%)
那我们下题见