題目:
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%)
那我們下題見