iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 17
0
自我挑戰組

Leetcode新手挑戰30天系列 第 17

#344 Reverse String

寫在開頭

今天選到這題只是在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後的結果
https://ithelp.ithome.com.tw/upload/images/20190918/20113393LSluFrfjTt.png

參考資料

參考1Python List reverse()方法


上一篇
#709 To Lower Case
下一篇
#231 Power of Two
系列文
Leetcode新手挑戰30天31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言