344. Reverse String
https://leetcode.com/problems/reverse-string
Python
Loop
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
length = len(s)
max_index = length - 1
for i in range(0, length//2):
s[i], s[max_index-i] = s[max_index-i], s[i]
Recursion
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
self._travel(s, 0, len(s)-1)
def _travel(self, s, left, right):
if left >= right:
return
s[left], s[right] = s[right], s[left]
self._travel(s, left+1, right-1)
Stack
class Solution:
def reverseString(self, s: List[str]) -> None:
stack = []
for char in s:
stack.append(char)
i = 0
while stack:
s[i] = stack.pop()
i += 1