LeetCode 筆記 - 344. Reverse String

題目在此 344. Reverse String

反轉字串

解題思維

這題也是 Two Pointers 大法的一種應用

這題我先使用 reversed index 的方法做出來
但看到課程標題是 Two Pointers,所以我就還是寫了一個 Two Pointers 的版本
(燦爛笑

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
# reversed index
# s[:] = [s[i] for i in reversed(range(len(s)))]

# two pointers
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]

left += 1
right -= 1

相關文章