今天選到這題只是在Easy裡面,看到這題的標題感覺應該是Easy,能夠解出來的.正好今天有點累不想要有想破頭想不通的問題,所以想挑這題來練習(哭笑)
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
這題我想到的方法,是用一個for迴圈,按照輸入的列表元素順序,從最後面一個個取出來,放到新列表的最前面,直到結束。或是把最後面的和最前面的元素,透過一個中介變數來互換。
所以應該像這樣:
def reverseString(self, s: List[str]) -> None:
temp = []
for i in s:
temp[len(s)-1] = i
s = temp
寫完去run code測試的時候跳出assignment index out of range,
才發現開頭宣告temp的時候沒有定義多長,後面放會有問題,
同時也查了一下python列表想回顧一下,找到了參考1,
發現其實python的list就有一個function是做反轉列表用的,
也不太需要自己用迴圈啥的,應該只需要這樣寫:
def reverseString(self, s: List[str]) -> None:
s.reverse()
測試果然就能跑過了,另外附上submit後的結果